DEV Community

Cover image for Introduction to Jest
kiraaziz
kiraaziz

Posted on

Introduction to Jest

Jest is a popular JavaScript testing framework created by Facebook. It is widely used for testing JavaScript code, including applications, libraries, and components. Jest provides an easy-to-use and intuitive API for writing tests and comes with built-in features like test runners, assertions, mocking, and code coverage reporting.

Installation

To begin, you'll need to install Jest in your project. You can install it using npm or yarn:

npm install --save-dev jest
Enter fullscreen mode Exit fullscreen mode

or

yarn add --dev jest
Enter fullscreen mode Exit fullscreen mode

Once Jest is installed, you can start writing tests!

Writing Your First Test

Create a new file in your project with the .test.js or .spec.js extension, such as mytest.test.js. This naming convention allows Jest to automatically discover and run your tests.

In your test file, you can write individual test cases using the test or it function provided by Jest. Here's a basic example:

// mytest.test.js

// Import the function you want to test
const { sum } = require('./myModule');

// Write a test case
test('adds 1 + 2 to equal 3', () => {
  // Call the function being tested
  const result = sum(1, 2);

  // Assert the expected outcome
  expect(result).toBe(3);
});
Enter fullscreen mode Exit fullscreen mode

In this example, we import the sum function from a module and write a test case to verify its behavior. The expect function is used to make assertions about the values produced by the code being tested.

Running Tests

To run your tests, you can use the following command:

npx jest
Enter fullscreen mode Exit fullscreen mode

This command tells Jest to look for all test files matching the *.test.js or *.spec.js pattern and execute them. Jest will provide a summary of the test results, including information about passed and failed tests.

Common Matchers

Jest provides a wide range of matchers that allow you to make assertions about the values produced by your code. Here are some commonly used matchers:

  • toBe(value): Asserts that a value is strictly equal (===) to the expected value.
  • toEqual(value): Asserts that a value is deeply equal to the expected value.
  • toBeNull(): Asserts that a value is null.
  • toBeDefined(): Asserts that a value is not undefined.
  • toBeTruthy(): Asserts that a value is truthy (not null, undefined, false, 0, NaN, or an empty string).
  • toBeFalsy(): Asserts that a value is falsy (either null, undefined, false, 0, NaN, or an empty string).
  • toContain(item): Asserts that an array or string contains the expected item.
  • toThrow(error): Asserts that a function throws an error.

These are just a few examples of the matchers provided by Jest. You can find a complete list in the Jest documentation.

Mocking Dependencies

In many cases, your code may depend on external modules or APIs. Jest allows you to easily mock these dependencies to control their behavior during testing. Here's an example:

// myModule.js

// A function that fetches data from an API
async function fetchData() {
  // ... implementation
}

// The main

 function that uses fetchData
async function processData() {
  const data = await fetchData();
  // ... process the data
  return processedData;
}

module.exports = { fetchData, processData };
Enter fullscreen mode Exit fullscreen mode
// myModule.test.js

const { fetchData, processData } = require('./myModule');

jest.mock('./myModule', () => ({
  fetchData: jest.fn(),
}));

test('processData calls fetchData and processes the data', async () => {
  fetchData.mockResolvedValue('mocked data');

  const result = await processData();

  expect(fetchData).toHaveBeenCalled();
  expect(result).toEqual('processed data');
});
Enter fullscreen mode Exit fullscreen mode

In this example, we mock the fetchData function using jest.fn() and provide a resolved value for it using mockResolvedValue. We then write a test case to verify that the processData function calls fetchData and processes the data correctly.

Testing Asynchronous Code

Jest provides several mechanisms to test asynchronous code, including promises, async/await, and callbacks. Here's an example using async/await:

// myModule.js

async function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('data');
    }, 1000);
  });
}

module.exports = { fetchData };
Enter fullscreen mode Exit fullscreen mode
// myModule.test.js

const { fetchData } = require('./myModule');

test('fetchData resolves with data', async () => {
  const result = await fetchData();

  expect(result).toEqual('data');
});
Enter fullscreen mode Exit fullscreen mode

In this example, the fetchData function returns a promise that resolves with the string 'data' after a delay of 1 second. The test case uses async/await to wait for the promise to resolve and then asserts the expected result.

Code Coverage

Jest provides built-in code coverage reporting, allowing you to see how much of your code is covered by tests. To enable code coverage, add the --coverage flag when running Jest:

npx jest --coverage
Enter fullscreen mode Exit fullscreen mode

Jest will generate a coverage report showing which lines of code are covered by tests and which are not. This helps identify areas of your codebase that lack test coverage.

Conclusion

This tutorial covered the basics of testing with Jest using Markdown. You learned how to write tests, use matchers for assertions, mock dependencies, test asynchronous code, and generate code coverage reports. Jest offers many more features and options for testing, so I encourage you to explore the official Jest documentation for more in-depth information.

Happy testing!

Top comments (0)