Javascript 使用MobX存储循环引用进行设置测试

Javascript 使用MobX存储循环引用进行设置测试,javascript,reactjs,unit-testing,jestjs,mobx,Javascript,Reactjs,Unit Testing,Jestjs,Mobx,我正试图通过我的MobX商店的玩笑来了解测试 我正在使用Mobx、React和Jest class ConfigStore { constructor(RootStore) { this.rootStore = RootStore; this.config = {}; } } class DataStore { constructor(RootStore) { this.config = RootStore.config;

我正试图通过我的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;
    }
}
通过这种方式,您可以确保始终正确更新和观察属性

如果您愿意,您可以始终在较低级别的存储上拥有属性:

class DataStore {
    constructor(RootStore) {
        this.configStore = RootStore;
    }
    get config() {
       return this.configStore.config;
    }
}
摘要 如果使用typescript将存储抽象为接口,那么存储将更易于测试:

class DataStore {
    constructor(store: IConfigStore) {
        this.configStore = store;
    }
}
interface IConfigStore {
     config: Config;
}
使用存储库模式 对于每个存储,使存储库可注入,以便存储完成的所有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调用

保持你的化学成分纯净 您真正想要进行单元测试的组件。确保他们不直接使用mobx存储,而是使用
inject()
函数创建第二个类:

这样,您的组件就更易于测试和独立使用:

const PureReactComponent = ({ name }) => <h1>{name}</h1>

const SimpleMobxComponent = inject(stores => ({
    name: stores.userStore.name
}))(PureReactComponent)

// usage:
render() {
  return <SimpleMobxComponent/>
}
constpureReactComponent=({name})=>{name}
常量SimpleMobxComponent=inject(存储=>({
名称:stores.userStore.name
}))(PureReactComponent)
//用法:
render(){
返回
}

谢谢您的回答。你能帮我解释一下存储库的概念吗?我也在用打字稿。谢谢。。。这看起来很棒!!请帮我理解。如何只为单个存储编写单元测试用例?2.当从useContext(RootStoreContext)钩子在组件中使用store时,如何编写测试用例?