Unit Testing with Jest

Unit Testing with Jest

Unit testing ensures individual parts of an application work correctly. It helps identify bugs early in the development process. Jest is a popular testing framework for JavaScript. It offers an easy setup and a robust feature set.

Getting Started

To start using Jest, install it via npm or yarn:

npm install --save-dev jest

or

yarn add --dev jest

This command installs Jest as a development dependency.

Next, add a test script to your package.json file:

"scripts": {
  "test": "jest"
}

This script allows you to run tests using npm test.

Writing a Test

Create a file named sum.js with a simple function:

function sum(a, b) {
  return a + b;
}
module.exports = sum;

This function adds two numbers and returns the result.

Next, create a test file named sum.test.js:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

This test checks if the sum function correctly adds 1 and 2 to get 3.

To run the tests, use the command:

npm test

Jest will automatically find and execute all test files.

Features of Jest

Snapshot Testing

Snapshot testing captures the output of a component and saves it to a file. If the output changes, Jest will alert you to update the snapshot.

Example of snapshot testing:

const renderer = require('react-test-renderer');
const React = require('react');
const MyComponent = require('./MyComponent');

test('renders correctly', () => {
  const tree = renderer.create(<MyComponent />).toJSON();
  expect(tree).toMatchSnapshot();
});

This test captures the rendered output of MyComponent and compares it to the saved snapshot.

Mock Functions

Jest can mock functions to isolate tests from their dependencies. This helps in testing functions independently.

Example of using mock functions:

const fetchData = require('./fetchData');

jest.mock('./fetchData');

test('fetches successfully', async () => {
  fetchData.mockResolvedValue({ data: 'value' });
  const result = await fetchData();
  expect(result.data).toBe('value');
});

In this test, fetchData is mocked to return a resolved promise with { data: 'value' }.

Running Tests

You can run specific tests by specifying the file:

jest sum.test.js

Use the --watch flag to rerun tests when files change:

jest --watch

This is useful for continuous testing during development.

To run only failed tests, use the --onlyFailures flag:

jest --onlyFailures

This focuses on rerunning only the tests that failed previously.

Conclusion

Jest simplifies unit testing in JavaScript projects. Its ease of installation, comprehensive features, and active community support make it an excellent choice for developers. With Jest, you can quickly write and run tests, ensuring your code behaves as expected. Install Jest, write your tests, and maintain robust, bug-free applications.

Vibe Plus 1

Sami Rahimi

Innovate relentlessly. Shape the future..

Recent Comments

Post your Comments (first log in)