[英]jest - testing mobx store @action TypeError: is not a function
I have the following store: 我有以下商店:
import { observable, action } from "mobx";
class UiStore {
@observable string;
constructor() {
this.string = "My string";
}
@action
setString = value => {
this.string = value;
};
}
export default UiStore;
And a simple test I am running with jest: 和一个简单的测试,我开玩笑:
import UiStore from "./UiStore";
describe("uiStore", () => {
it("setString sets string to the passed value", () => {
const uiStore = new UiStore();
uiStore.setString("blah");
expect(uiStore.string).toBe("blah");
});
});
But I am getting the following error: 但是我收到以下错误:
TypeError: uiStore.setString is not a function
TypeError:uiStore.setString不是函数
When I remove the @action
decorator, the test will pass. 当我删除
@action
装饰器时,测试将通过。 But according to the mobx docs , the @action
decorator significantly increases performance when the functions are modifying state. 但是根据mobx文档 ,当函数修改状态时,
@action
装饰器会显着提高性能。 Does anybody know of a way to test mobx @actions? 有人知道测试mobx @actions的方法吗?
Not using a arrow function solves this problem: 不使用箭头功能可解决此问题:
import { observable, action } from "mobx";
class UiStore {
@observable string;
constructor() {
this.string = "My string";
}
@action
setString(value) {
this.string = value;
}
}
export default UiStore;
No idea why though... 不知道为什么...
In order for decorators to work with class field methods you must ensure that when using the transform-decorators-legacy
and transform-class-properties
plugins that you put them in the right order in your .babelrc
, for example: 为了使装饰器能够使用类字段方法 ,必须确保在使用
transform-decorators-legacy
和transform-class-properties
插件时, .babelrc
它们以正确的顺序放在.babelrc
,例如:
Incorrect ✖ 错误✖
"plugins": [
"transform-class-properties",
"transform-decorator-legacy",
]
Correct ✔ 正确✔
"plugins": [
"transform-decorator-legacy",
"transform-class-properties",
]
Alternatively you may use the @action.bound
decorator on a class method, which will bind it as if it was a class field method, as Miha suggested in his answer. 或者,您可以在类方法上使用
@action.bound
装饰器,这将绑定它,就像它是类字段方法一样,正如Miha在他的回答中所建议的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.