Test a React Applications using MobX with Jest

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 4 years ago

MobX is independent of React and really you can use whatever testing framework you want with it. Testing MobX is essentially as easy as testing simple JavaScript.

This lesson demonstrates an example of testing mobx application state with Jest.

Instructor: [00:00] Here, we have a simple list application from a previous lesson. It allows us to add items and reset the items, if required. The behavior of this application is described by the application state class. In order to test the application behavior, we can go a long way by simply testing that the app state behaves as expected.

[00:29] Since all we need to do is test simple JavaScript, we can use any testing framework like Mocha, Jasmine, or Jest with MobX. Let's go with Jest as that is the most common one used by React developers.

[00:46] We already have Jest set up using the standard Typescript Jest process. We have a script target to run Jest. Installation was a simple npm install of the types, Jest, Jest itself, and ts-jest.

[01:06] We've also configured Jest with the simple copy-paste of jest.config.js from our Typescript React course. Now, let's go ahead and add a test for the app state. You will test all the features that are provided by app state in individual tests.

[01:28] We create a test file. Bring in the singleton app state. Before each test, you will go ahead and reset the app state to its initial state. To test that it is going to store a list of items, we simply check the initial items to be an empty array.

[01:55] Next, to allow maintaining a current string as it gets typed, we check that the initial value is an empty string. Then, we simulate a user type of character A, and ensure that the current item updates.

[02:14] Next, we type another character to make the value AB, and ensure that the current item updates accordingly. To test the ability to add this current string to the list of items, we will go ahead and change the current item to some value and add it to the list.

[02:41] We expect the list to contain this item. For the option to reset the items in the current string, we simply add a current item to the list. We then reset the app state and expect the initial conditions.

[03:10] Now, let's go ahead and run the test in the terminal using npm-t. You can see that the test passed with flying colors. Notice that as MobX is transparent reactive, you get to write simple JavaScript tests for your state behavior without having to go through complex APIs and patterns.

[03:42] A neat feature of Jest is built in coverage support that you can activate with the minus minus coverage flag. You can see that our tests cover 100 percent of the application state behavior.