【问题标题】:Setup testing with MobX store circular references使用 MobX 存储循环引用设置测试
【发布时间】:2018-05-16 18:07:51
【问题描述】:

我正在尝试使用 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);
    }
}

我的商店设置是否正确?

如果是这样,在将商店传递给 Provider 之前对其进行测试的最佳方法是什么?

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs mobx


    【解决方案1】:

    你的问题很不清楚。您究竟想在单元测试中对这些商店进行哪些测试?你不能真正测试数据本身。

    我的建议:

    商店链接

    不要使用设置单个属性,而是保留整个商店:

    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() 函数来创建第二类: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/>
    }
    

    【讨论】:

    • 感谢您的回答。你能帮我解释一下存储库的概念吗?我也在使用打字稿。
    • 谢谢...这看起来很棒!!请帮我理解 1.如何为单个商店编写单元测试用例? 2. useContext(RootStoreContext) hook在组件中使用store时如何编写测试用例?
    猜你喜欢
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    相关资源
    最近更新 更多