Best Practices for Using Jest with React
General
- Prefix mock variables with the word
mock
to preventout-of-scope reference
errors and improve clarity. - Store mocked variables in a
.mock
file and import them into the.test
files. If any modifications are needed, create a cloned variable within the.test
file and apply the changes there. This approach makes it easier to track differences in variables for different test cases while minimizing the number of mock variables maintained. - Each test should contain only a single
expect
statement. - The names of the test suite and test cases should be structured to form a meaningful sentence, making it clear what is being tested. They should be understandable to any product owner, providing insight into the areas covered by the tests.
- leverage the feature of snapshot testing, as it can be useful for detecting unintended component changes.
Basic Tests
- The optional parameter of a method should be tested with
null
. - The optional parameter of a method should be tested with
undefined
. Arrays
andobjects
are similar in how they’re structured, so sometimesobjects
can pass tests that are meant forarrays
. However, sincearrays
have special methods and behaviours, we should write more detailed tests for them.- Whenever a function is supposed to return an array, always use
Array.isArray()
in your tests to check if the result is actually an array. This makes sure the function works correctly with arrays and not just objects that look like arrays.
Mocking
- Jest is used for writing unit tests, and when doing so, the focus should be on the “unit,” or the current source file. Therefore, any external dependencies should be mocked.
- All dependencies, including imports from your own project or third-party libraries, must be mocked.
- Use
jest.fn()
to mock these dependencies.
Cleanup and Reset
Often, cleanup is required before or after each unit test. Use the beforeEach
and afterEach
blocks to handle Jest cleanups.
Method to Render React Component
Create a method that renders the Test component and use this method to generate instances of the Test component. You can pass props and mock the Redux store to this method, helping to keep the code maintainable.