Skip to content Skip to sidebar Skip to footer

How Can I Test A Store Singleton?

I already am implementing unit tests using redux-mock-store. I would like to perform an integration test suite on a react-native app that uses store singletons just fine. However e

Solution 1:

I'll answer my question as a mean for others to work on this casuistic.

As in many other tutorials and guides, store singletons are discouraged. Which I understand is a matter of isolating dependencies and components. However if you still decide to use it for comfort –as we do– you'll need to mock the component when required from other deps, as they are not going to be mocked recursively.

So apart form having a similar to this, folder structure...

.
├── app
|    ├── __mocks__
|    |    |
|    |    └── store.js
|    └── store.js

You'll need to export the mocked version, for those deps that require './store.js' at the same time.

// app/store.js// Choose mock dependency over current store for testsif (process.env.NODE_ENV === 'test') {
  jest.mock('./store')
}

This way, whenever store.js is required during tests, it will recursively choose the mock version over the real one.

Probably store singletons need a little more advocacy to be chosen as a mainstream redux practice. Should not be considered an anti-pattern.

Post a Comment for "How Can I Test A Store Singleton?"