Jest Tutorial: Writing Test Cases Using Jest

In this Jest Tutorial, we will be covering the process of writing test cases for your JavaScript code using the popular testing framework Jest. This tutorial will guide you through the basics of setting up your project, writing test cases and running your tests.

By the end of this Jest tutorial, you will have a good understanding of how to use Jest for building reliable and robust JavaScript code. The tutorial is suitable for both beginners and experienced developers. You will learn about the key concepts of Jest and how to implement them in your projects.

What Is Unit Testing?

Unit testing is a method of software testing in which individual components of the software are tested. The goal of unit testing is to ensure that each component of the software functions as expected. This is done by breaking the software down into smaller, testable parts and then testing each part individually.

By doing this, any mistakes or errors in the code can be uncovered and corrected early on in the development process. This not only helps to improve the overall quality of the software, but it also makes it easier to identify and fix any issues that may arise in the future. Additionally, having a set of unit tests can serve as documentation for new team members, allowing them to understand how the existing code works by reading the tests.

Tools available for testing: A variety of tools are available to test React Native applications, some of which are the following:

  • WebDriver
  • Nightmare
  • Jest
  • Mocha
  • Jasmine

Advantages Of  Writing Test Cases

1. Whenever we add new features, we can test previous test cases to track whether new features impact previous features.

2. Refactoring gets easier.

3. When we upgrade dependencies configured in the project.

What Is Jest ?

Jest is a JavaScript testing framework that is developed specifically for React applications. Developed and used by Facebook, Jest provides a set of features for organizing and running tests. Its main purpose is to ensure the correctness of any JavaScript codebase.

With Jest, you can test all types of JavaScript code, including React applications. Jest acts as a test runner, finding and running all test files that end with .test.js and are located within the test folder. It will then determine whether the tests have passed or failed and provide a coverage table. In case of failure, Jest will indicate why and where the test failed.

In the next step we will see the process of installing Jest.

How To Install Jest ?

1. Starting from react-native version 0.38, By default, a Jest setup is included when running react-native init. 

2. The below configuration should get automatically added to your package.json file:

3. Here –coverage returns coverage report of how many parts of the code are covered for testing by test cases

4. For more Jest, CLI option can refer link: Here

5. Run yarn test or npm test to run tests with Jest.

How Do We Configure Jest In React Native Project ?

1. Sometimes you need more config by creating a file named jest.config.js|ts|mjs|cjs|json.

2. You can use the –config flag to pass an explicit path to the created config file.

Jest API

1. In reacts native project while writing test cases in a test file, all the methods and objects from Jest are included in its global environment. You can use them directly without importing them. 

2. However, if you prefer explicit imports, you can import from @jest/globals package

 import {expect, test, describe} from '@jest/globals.'

Mostly used methods from the global box of jest API are as below:

1. afterAll(fn, timeout) : 

– This runs a function after completing all the tests defined in the file.

– Optionally, we can provide a timeout (in milliseconds) here to specify how long to wait before aborting. The timeout interval is 5 seconds by default.

– Ex: Can be used to clean up the database. 

2. afterEach(fn, timeout):

– This runs a function after each of the tests defined in the file. 

– Optionally, we can provide a timeout (in milliseconds) here.

3. beforeAll(fn, timeout):

– This runs a function before completing all the tests defined in the file.

– Optionally, we can provide a timeout.

– Ex: Can be used to set up global states like server setup.

4. describe(name, fn): Used to define a set of tests. Also called a test suite.

5. test(name, fn, timeout): Allows to write a test by specifying test name and actual test written in its callback function. Timeout is optional here.

6. expect(value): 

– While writing tests, we often need to check that values meet certain conditions. Expect provides several matcher functions which allow us to validate different conditions.

– The expect function is used when we want to test a value. 

– Expect used along with the matcher function to perform assertion.

– This can be used to assert test value with the expected one.

Refer to this link to check more API.

Matchers

  • Jest uses matcher functions to test values in different ways
  • Common matcher:

Ex: test(‘two plus two is four’, () => {

  expect(2 + 2).toBe(4);

});

  1. toBeNull matches only null
  2. toBeUndefined matches only undefined
  3. toBeDefined is the opposite of toBeUndefined
  4. toBeTruthy matches anything that an if statement returned as true
  5. toBeFalsy matches anything that an if statement returned as false
  6. expect(value).toBeGreaterThan(4);
  7. expect(value).toBeGreaterThanOrEqual(4.5);
  8. expect(value).toBeLessThan(6);
  9. expect(value).toBeLessThanOrEqual(6.5);

Refer to this link to check more matcher functions.

Jest is recommended by React testing lib. React testing lib with Jest provides a certain set of practices. I have described testing lib in more detail below.

What Is The Use Of React Testing Library?

React Testing Library is a lightweight testing library that allows you to test React components. It provides a set of tools and a virtual DOM to make it easier to test your components. This library provides a set of functions which help to find and interact with specific DOM nodes from within the component that needs to be tested.

React Testing Library helps with the process of rendering the component into a virtual DOM using the “Render” method. It also makes it easy to search and interact with the virtual DOM. One of the most important benefits of using this library is that it provides utility functions on top of react-test-renderer, which encourage better testing practices and more robust test suites.

Mocking

A mock function is a function that defines a fake or mocked implementation of code that replaces the actual performance. By using mock functions, we can know the result returned by the function, the number of times the function was called, and the arguments used when calling the function.

This helps to test the code in isolation and makes the testing process more predictable. Mock functions are particularly useful for testing, as they allow us to override the actual behavior of a function with custom mock implementations.

With these mock implementations, we can control the return values of a function, making it easier to write tests. Jest provides a utility function, jest.spyOn(), which can be used to create a mock function. Using this function, you can track the calls, arguments and return values of a function, and even change the behavior of a function on the fly to test different scenarios.

The Mock Function provides features to:

  • Capture calls
  • Set return values as per our test case requirement
  • Change the implementation to have control over our test

A mock function instance is created with jest.fn()

Mocking return values: To mock a function’s return value in Jest, First, you need to import all named exports from a module, then you can define mockReturnValue on the imported function.

Hire Our Expert React Native Developers

If you want to mock the return value of a function differently based on consecutive calls of the defined returned value, you can use a define as a chain of mockReturnValueOnce.

The mockImplementation call to mock the return value of your function is another way to mock the return value. However, unlike mockReturnValue, this can mock the entire implementation of your mock functions, not just their return values.

Note that jest. fn(implementation) is shorthand for mockImplementation. Therefore the functionality remains the same. Lastly, mockImplementationOnce can also be used to mock the return value differently for each consecutive call, just like mockReturnValueOnce.

Function Mock Using  jest.spyOn()

Jest.spyOn() method also can be used to create a functioning mock. Same as a jest.fn(), it makes a controlled mock. The main key difference is the fact that by default, jest.spyOn() calls the original implementation.  

By using jest.spyOn(), the original implementation is stored in memory so that it can be restored. The initial implementation can be fixed using the mockRestore() method, which can not be done using jest. fn(). There is one more type of testing I am going to explain in brief, which can be done to test UI.

Snapshot Testing

Snapshot tests are a useful tool that helps ensure your UI does not change unintentionally or unexpectedly. A snapshot test case renders a UI component, takes a snapshot then compares it with a snapshot file stored along with the test as its reference. The test will fail if two snapshots do not match.

The main purpose of snapshot testing is to ensure that an application’s user interface (UI) should not get changed unexpectedly or unintentionally, which captures the screenshot at a specific moment in time so that it can be compared in the future. Snapshot testing allows you to verify that the structure of your components has not changed by catching unintended change

Eg Home-test.js

From the above example, We import the renderer from the react-test-renderer package. This package can render react components to pure js objects without depending on the DOM or native mobile environment. This package makes it easy to grab a snapshot of the platform view hierarchy rendered by a React DOM or React native component without using a js dom.

In the above example, In the body of the test, we render the Intro component and convert it to JSON, Then compare it with the previously saved snapshot file. The following commands are used to run snapshot test cases.

Run command: npm test

The snapshot folder is auto-generated using the above command.

Run command: npm test – -u (to update screenshot)

Writing And Running Tests

To write test cases using Jest in react native first import render function from @testing-library/react library. It will be used to render the component you want to test.  Then, render provides various methods to perform assertions about the component’s behavior.

For example, You could use any render method to check the component’s specific action, like suppose the getByText process to check that the button component has text rendered which is correct or the click method to test some steps.

You can use the jest command in the terminal to run the test. Jest, by default, will search test files and run any files which end with .test.js and matches patterns __test__/*.

coma

Conclusion

In conclusion, this Jest tutorial has provided an overview of how to use Jest and the testing library to write test cases for React Native applications. Developers can now implement Jest and testing library in their own projects to ensure their code is working as expected and to catch any bugs before they are released to users.

By using Jest and testing library, developers can also feel confident in the reliability and stability of their code, giving them peace of mind and a greater ability to focus on new features and improvements. With Jest and testing library, developers can ensure that their code is of high quality and that it is functioning correctly, making it a powerful tool for any React Native developer.

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!