-2

When mobx store is used from useContext() hook what will be best approach to write unit test case? Should we use enzyme or react testing library? Here Provider or @inject() is not used

Store design:

//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());

In component store is used from useContext hook

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

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

In below scenario,

  1. How to write Unit test case only for individual stores (its having circular dependency)
  2. If react testing library used, how to mock stores and useContext?
  3. Is it possible to use enzyme?
  4. Which lib's are suitable for writing UTC?
ksh
  • 448
  • 6
  • 19

1 Answers1

0

If you are just unit testing the stores, don't use components. Instantiate the stores directly and test them.

If you are testing component interaction (integration) then I would suggest you use the react testing library. Create the context provider and wrap you components with the provider for each test.

more info: https://testing-library.com/docs/example-react-context

Ivan V.
  • 4,134
  • 2
  • 21
  • 38