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

标签 javascript reactjs unit-testing jestjs mobx

我正在尝试用 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/

相关文章:

css - 如何删除 React Bootstrap 中按钮上事件状态的轮廓?

javascript - 类型错误 : undefined not a constructor when using beforeEach in jasmine test

android - 我如何在android中为挂起功能和状态流编写单元测试

javascript - jQuery Counter, animation to a total,但我如何包含一个逗号?

JavaScript 对象实例化

javascript - Javascript 中 URL 的 HTTP 状态代码

reactjs - observable.takeUntil... 和 observable.pipe(takeUntil) 之间的区别

javascript - 当我在渲染中包装组件时,函数作为 React 子项无效

java - 测试 Spring 存储库 - 始终无法正确调用 EntityManager 加载和删除

javascript - 使用 vanilla JavaScript 向下滚动时隐藏菜单,向上滚动时显示菜单