我正在尝试用 Jest 来测试我的 MobX 商店。
我正在使用 Mobx、React 和 Jest。
class ConfigStore {
constructor(RootStore) {
this.rootStore = RootStore;
this.config = {};
}
}
class DataStore {
constructor(RootStore) {
this.config = RootStore.config;
}
}
class UIStore {
constructor(RootStore) {
this.config = RootStore.config;
this.data = RootStore.data;
}
}
class RootStore {
constructor() {
this.config = new ConfigStore(this);
this.ui = new UIStore(this);
this.data = new DataStore(this);
}
}
我的商店设置是否正确?
如果是这样,在商店传递给提供商之前测试商店的最佳方法是什么?
最佳答案
你的问题很不清楚。您到底想在单元测试中测试这些商店的哪些内容?您无法真正测试数据本身。
我的建议:
商店链接
不要使用设置单个属性,只需保留整个商店:
class DataStore {
constructor(RootStore) {
this.configStore = RootStore;
}
}
这样您就可以确保属性始终得到正确更新和观察。
如果您愿意,您可以随时在较低级别的商店中拥有属性(property):
class DataStore {
constructor(RootStore) {
this.configStore = RootStore;
}
get config() {
return this.configStore.config;
}
}
摘要
如果您使用 typescript 通过接口(interface)抽象您的商店,以便更容易测试商店:
class DataStore {
constructor(store: IConfigStore) {
this.configStore = store;
}
}
interface IConfigStore {
config: Config;
}
使用存储库模式
为每个商店创建一个可注入(inject)的存储库,以便商店完成的所有 api 调用实际上都在此存储库中完成:
class RootStore {
constructor(repository) {
this.repostiory = repository;
this.config = new ConfigStore(this);
this.ui = new UIStore(this);
this.data = new DataStore(this);
this.initializeData();
}
async initializeData(){
this.config = await this.repository.getConfig();
}
}
这样您就可以轻松模拟存储库以提供静态日期,这样您就不需要执行任何 api 调用。
保持你的 react 组件纯净
您真正想要进行单元测试的 react 组件。确保它们不直接使用 mobx 存储,而是使用 inject()
函数来创建第二个类:https://github.com/mobxjs/mobx-react#inject-as-function
这样您的组件就更容易测试并且可以独立使用:
const PureReactComponent = ({ name }) => <h1>{name}</h1>
const SimpleMobxComponent = inject(stores => ({
name: stores.userStore.name
}))(PureReactComponent)
// usage:
render() {
return <SimpleMobxComponent/>
}
关于javascript - 使用 MobX 存储循环引用进行设置测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50377448/