Javascript jest-测试mobx store@action TypeError:不是函数
我有以下商店:Javascript jest-测试mobx store@action TypeError:不是函数,javascript,ecmascript-6,jestjs,mobx,Javascript,Ecmascript 6,Jestjs,Mobx,我有以下商店: import { observable, action } from "mobx"; class UiStore { @observable string; constructor() { this.string = "My string"; } @action setString = value => { this.string = value; }; } export default UiStore; 我在开玩笑地做一个
import { observable, action } from "mobx";
class UiStore {
@observable string;
constructor() {
this.string = "My string";
}
@action
setString = value => {
this.string = value;
};
}
export default UiStore;
我在开玩笑地做一个简单的测试:
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");
});
});
但我得到了以下错误:
TypeError:uiStore.setString不是函数
当我删除
@action
装饰器时,测试将通过。但是根据,当函数修改状态时,@action
装饰器会显著提高性能。有人知道测试mobx@actions的方法吗?不使用箭头函数可以解决此问题:
import { observable, action } from "mobx";
class UiStore {
@observable string;
constructor() {
this.string = "My string";
}
@action
setString(value) {
this.string = value;
}
}
export default UiStore;
不知道为什么…为了让装饰程序使用类字段方法,您必须确保在使用transform decorators legacy
和transform class properties
插件时,将它们按正确的顺序放在中。例如:
不正确✖强>
"plugins": [
"transform-class-properties",
"transform-decorator-legacy",
]
正确✔强>
"plugins": [
"transform-decorator-legacy",
"transform-class-properties",
]
或者,您也可以在类方法上使用@action.bound
装饰程序,就像Miha在回答中所建议的那样,它将类方法绑定为类字段方法。。。装饰器使用类方法。您以前拥有的是一个类字段(property,或w.e.its,现在被称为)setString=value=>{this.string=value;}问题代码中的code>将生成绑定函数。您可能需要@action.bound setString(value){this.string=value;}
奇怪的是,它在我的浏览器中运行良好,修饰的类字段属性方法仅在测试运行期间失败。我找到了答案。我在测试套件中遇到此错误,但在浏览器中没有遇到,因为每个测试套件都有单独的babel配置。有关更多信息,请参阅我的。