This post assumes familiarity with MobX.
In my previous post (if you haven't read, please do)
I had shown two simple examples of how to use MobX custom hooks via the
mobx-react-lite package and how to use the traditional MobX class stores via the built-in
useContext hook. In this post, I will demonstrate how to test these components that use hooks via Kent C. Dodds superb react-testing-library. Do check the documentation for how to render your React components in tests.
I am using the same CodeSandbox examples used in my previous post for simplicity. Also you can view the tests and output at the same time.
For the first example, in which we use the
useObservable hook, the component is easy to test.
If you view the
index.test.js file, there are two tests,
- to check whether the list has rendered.
- to test whether the todos toggle changes the remaining items.
In the first test, we check the length of the list-items and the footer text, using the Jest
In the second test, we fire a click event on the list-items using the
fireEvent method in which the
toggleTodo method is fired that changes the todo's
completed parameter. This in turn changes our Footer components' text which we can again test using Jest assertions.
For the second example, to test the MobX class which we used in our component via
useContext, we need to create a dummy component and import our store as we would normally do in any other component.
If you view the
index.test.js file, a dummy component is created and it consumes our MobX class store using the
useContext hook. We just define the minimal UI we need to test according to our MobX store and write our tests.
The tests are same as the first example but the only change here is we create a dummy component to test our MobX store to mimic our main React component.
To view the output of the tests, you can open the tests panel at the bottom of the editor in which CodeSandbox runs the test automatically for you.
Feel free to fork the sandbox and play around with those tests and components. Thanks for reading!