Testing in react.js is tricky due to its lifecycle hook implementation. In this project, I have implemented a product listing app using the TDD approach. I have used Jest, Enzyme, and its many features to tackle the tricky areas around react.js testing. The tests use mock data to simulate async data fetches for the products. Enzyme has features that allow us to test components in shallow or mounted mode. Mounted mode allows us to test the component with all its child components loaded. The app will make a rest call to fetch products, when JSON response is received the data is used to render the product list with such details as title, price, and an image link. The final result is as seen in the screenshot above. See the full code on Github
You will notice that in the folder structure there is a folder called __mocks__, this folder contains the mock functions that will mock the async calls to fetch data. With Jest, you can replace functions with mock functions. For this we will write a line of code similar to : jest.mock(“./services/fetchProductList”);
- productListing.jsx (Component fetches and displays product list)
- productListing.spec.jsx (TDD tests written with Jest and enzyme)
- setupTests.js (Settings for enzyme testing)
- fetchProductList.jsx (Component to fetch product list asynchronously)
- __mocks__ (contains code to mock async calls to fetch product list)
To install and test the app
to run tests …
The screenshot below shows that all tests have been successful
to run the app …
… a bit about the tests
We will be testing the productListing component, the tests for this component is contained in productListing.spec.jsx.
There is a wait function declared at the top. This little function is useful in dealing with reacts lifecycle hooks. So that our tests can be in sync with reacts lifecycle hooks, we will wait for the views to be fully rendered before continuing.
The tests also use Jest mock features to substitute functions when in test mode. I have highlighted the areas of interest below.
You can inspect and review the commits to this repository to understand the TDD approach. I have written the commit messages in a way its easy to understand the TDD approach taken.