Best Practices for Using Jest with React

Yuvraj Patil
2 min readFeb 12, 2025

--

Photo by Lucas Vasques on Unsplash

General

  • Prefix mock variables with the word mock to prevent out-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 and objects are similar in how they’re structured, so sometimes objects can pass tests that are meant for arrays. However, since arrays 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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yuvraj Patil
Yuvraj Patil

Written by Yuvraj Patil

Riding the dragon in realm of React Native. Website: https://.www.yuvrajpatil.com

No responses yet

Write a response