Jest Testing
Jest is a popular open-source testing framework for JavaScript-based frameworks. It comes with a range of exciting features to make test writing and execution simple for developers. For example, Jest supports data mocking, snapshot testing, watch mode, and built-in test runners, and it can be used with zero configuration.
In fact, according to the State of JavaScript 2023 survey, Jest is the most used JavaScript testing framework among developers. It also has 44K+ GitHub stars and over 33 million weekly NPM downloads.
Key Features in Jest Testing
- Zero configuration: Jest works out of the box with minimum non-complex setups. A common React or Node.js setup can kickstart testing immediately.
- Mocking: Jest has built-in support for mocking functions, modules, and timers. This is beneficial for isolating the code that needs to be tested.
- Snapshot testing: Snapshots are implemented in Jest to verify large objects’ integrity without needing detailed assertions. By taking a snapshot of your component’s rendered output, you can easily compare it with future versions to spot any changes.
- Parallel test execution: Jest supports test execution in parallel. Each test is run in its own process, helping to significantly reduce the test execution time.
- Code coverage: Jest has the capability to generate code coverage reports, allowing you to discover the untested parts of your code.
- Watch mode: The watch mode facilitates rerunning only the tests that have been modified, resulting in an acceleration in the feedback loop.
Setting UP Jest
Setting up Jest is a pretty straightforward task:
Step 1: Installing Jest
Like any other application, Installing Jest will be our first step. We could use npm syntax or yarn syntax to install Jest.
Using npm:
npm install --save-dev jest
Using yarn:
yarn add --dev jest
Sep 2: Configuring Jest
There are two approaches to follow while configuring Jest.
Jest configuration in your **package.json**
Adding a test script and optional Jest configuration:
{ "scripts": { "test": "jest" }, "jest": { "verbose": true } }
Creating **jest.config.js** file in your project root
module.exports = { verbose: true, };
3. Creating a Test File
To create a test file, follow these steps:
- Option 1: Create a test directory in your project, which typically stores all the test files __tests__.
- Option 2: Place the test files next to the corresponding module files and add a .test.js or .spec.jssuffix to their names.
Let’s take a look at an example:
Create a file named sum.js:
// sum.js function sum(x, y) { return x + y; } module.exports = sum;
Then, create the corresponding test file named sum.test.js:
// sum.test.js const sum = require('./sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
4. Running Tests
Created test files can be run using both npm and yarn commands.
npm test
yarn test
So far, we have discussed the initial setup and running of the tests in Jest. Let’s now look at the commands and syntax for advanced features in Jest that make it stand out from its competitors.
1. Watch Mode
Watch Mode is a powerful feature in Jest that simplifies the development process by automatically rerunning relevant tests if any code has been modified.
Enabling Watch Mode syntax: npm test — –watch
Watch Mode has various control commands to run:
- Run all tests: By default, Jest only runs tests related to modified code. You may press “a” to run all tests.
- Filter by file name: Entering a part of a file name will run tests related only to that file.
- Filter by test name: Pressing “t” filters and runs specific tests that match a search term.
- Exit watch mode: Press “q” to exit watch mode.
Immediate feedback, efficient development, and focus on relevant tests are key benefits of watch mode.
2. Mock Functions
Mocking helps simulate and control the behavior of functions and modules during testing. It is a great way to isolate the code being tested and verify its interaction with the respective dependencies. Furthermore, mock functions can track calls, arguments, and return values.
- Create Mock Function: Mock function can be created in Jest using
jest.fn(). const mockFunction = jest.fn(); mockFunction(); expect(mockFunction).toHaveBeenCalled(); // Verifies that the function was called
- Mock Customization: You can customize mock functions by controlling their return values or full implementation using
mockReturnValue() and mockImplementation(). const mockFunction = jest.fn().mockReturnValue('Hello, World!'); expect(mockFunction()).toBe('Hello, World!');
- Mock Resetting: To reset mocks between tests, mockClear() or mockReset() can be used.
const mockFunction = jest.fn().mockReturnValue(5); mockFunction(); expect(mockFunction).toHaveBeenCalledTimes(1); mockFunction.mockClear(); // Clears call history expect(mockFunction).not.toHaveBeenCalled();
- Module Mocking: Entire modules can be mocked using jest.mock().
jest.mock('./apiModule'); // Mocks the 'apiModule' module const apiModule = require('./apiModule'); apiModule.getData.mockReturnValue({ id: 1, name: 'Test' }); expect(apiModule.getData()).toEqual({ id: 1, name: 'Test' });
- Verification: To assert on calls and arguments, matchers such as toHaveBeenCalled() can be used.
const mockFunction = jest.fn(); mockFunction('arg1', 'arg2'); expect(mockFunction).toHaveBeenCalledWith('arg1', 'arg2');
3. Snapshot Testing
Snapshot testing in Jest is a user-friendly way to detect changes in UI components or larger objects, such as JSON responses from API endpoints. It compares the output from a previous test run with the current output, highlighting any discrepancies.
import React from 'react'; import { render } from '@testing-library/react'; import MyComponent from './MyComponent'; test('it matches the snapshot', () => { const { asFragment } = render(<MyComponent />); expect(asFragment()).toMatchSnapshot(); });
This code sets up a snapshot test for MyComponent using React and @testing-library/react. The asFragment() function is used to capture the rendered output, which is then compared to a stored snapshot to detect any changes.
Key Advantages of Jest
These are some major benefits you get when using Jest in your project.
- It has a large and active community.
- It is commonly used with popular frameworks like React, Angular, Vue, and Node.js.
- It works well with tools like Babel, TypeScript, and ESLint.
- You can cover all your testing needs, from unit tests to integration and end-to-end testing.
- It is regularly updated with new features.
Conclusion
Jest is a powerful unit testing framework that helps you write more reliable and maintainable code. It encourages good testing standards and practices and helps you discover issues earlier in development. Regardless of the complexity of the project, Jest provides the tools you require to ensure the quality and stability of your codebase.