微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Mobx + RootStore + useContext挂钩时的单元测试用例

如何解决Mobx + RootStore + useContext挂钩时的单元测试用例

在useContext()钩子中使用mobx存储时,什么是编写单元测试用例的最佳方法?我们应该使用酶还是反应测试库?这里不使用Provider或@inject()

商店设计:

//StoreA
export class StoreA {
  rootStore: RootStore;
  constructor(rootStore: RootStore) {
    this.rootStore = rootStore;
  }
  //StoreA implementations...
}

 //StoreB
export class StoreB {
  rootStore: RootStore;
  constructor(rootStore: RootStore) {
    this.rootStore = rootStore;
  }
  //StoreB implementations...
}

//RootStore
export class RootStore {
  StoreA: StoreA;
  StoreB: StoreB;
  constructor() {
    this.storeA = new storeA(this);
    this.storeB = new storeB(this);
  }
}

export const RootStoreContext = createContext(new RootStore());

在组件存储中通过useContext挂钩使用

const SomeComponent = ({}) => {
  const rootStore = useContext(RootStoreContext);
  const { storeAdata,storeAmethods } = rootStore.storeA;
  //Component code....
}

Stackblitz链接https://stackblitz.com/edit/react-ts-qec5vu?file=Hello.tsx

在以下情况下,

  1. 如何仅针对单个商店(具有循环依赖性)编写单元测试用例
  2. 如果使用了React测试库,如何模拟存储和useContext?
  3. 可以使用酶吗?
  4. 哪个库适合编写UTC?

解决方法

如果您只是对商店进行单元测试,请不要使用组件。直接实例化商店并进行测试。

如果您正在测试组件交互(集成),那么我建议您使用react测试库。创建上下文提供程序,并为每个测试使用提供程序包装组件。

更多信息:https://testing-library.com/docs/example-react-context

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。