MobX makeObservable 不适用于 Jest

MobX makeObservable does not work with Jest

我正在尝试使用 Jest 测试我的商店,当我使用 makeObservable 时,出现以下错误:

[MobX] Cannot apply 'observable' to 'TodoStore@3.todos': Field not found.

      23 |
      24 |   constructor() {
    > 25 |     makeObservable(this, {
         |                   ^
      26 |       todos: observable,
      27 |       filter: observable
      28 |     })

      at die (node_modules/mobx/src/errors.ts:84:15)
      at ObservableObjectAdministration.make_ (node_modules/mobx/src/types/observableobject.ts:250:17)
      at forEach (node_modules/mobx/src/api/makeObservable.ts:37:49)
          at Array.forEach (<anonymous>)
      at makeObservable (node_modules/mobx/src/api/makeObservable.ts:37:30)
      at new TodoStore (src/typings/models/ToDoStore.ts:25:19)
      at tests/looseReplaceNodes.test.ts:76:17
      at step (tests/looseReplaceNodes.test.ts:33:23)
      at Object.next (tests/looseReplaceNodes.test.ts:14:53)
      at tests/looseReplaceNodes.test.ts:8:71

Class 问题:

export class TodoStore {
  todos: Todo[]
  filter: string

  constructor() {
    makeObservable(this, {
      todos: observable,
      filter: observable
    })
    this.todos = []
    this.filter = ""
  }
  createTodo(value: any) {
    this.todos.push(new Todo(value))
  }
}

当我改为使用 makeAutoObservable 时,这会消失,但这对我的用例不起作用(这是一个玩具示例)。我不想使用装饰器,因为 MobX 似乎正在远离它。

有什么想法吗?

最简单的方法就是这样重写:

export class TodoStore {
  todos: Todo[] = []
  filter: string = ""

  constructor() {
    makeObservable(this, {
      todos: observable,
      filter: observable
    })
  }
  createTodo(value: any) {
    this.todos.push(new Todo(value))
  }
}

Or check configuration that you need to apply:

TypeScript: 设置编译选项"useDefineForClassFields": true.

Babel:确保至少使用 7.12 版本,配置如下:

{
    "plugins": [["@babel/plugin-proposal-class-properties", { "loose": false }]],
    // Babel >= 7.13.0 (https://babeljs.io/docs/en/assumptions)
    "assumptions": {
        "setPublicClassFields": false
    }
}

通常最好在构造函数中最后调用 make(Auto)Observable,或者立即定义属性。