DEV Community

Cover image for Test Your JavaScript App With Jest
Jospin Ndagano
Jospin Ndagano

Posted on

Test Your JavaScript App With Jest

Testing is a crucial part of software development that ensures your application behaves as expected. One of the most popular testing frameworks in the JavaScript ecosystem is Jest. Developed by Facebook, Jest is known for its simplicity and ease of use, making it an excellent choice for both beginners and experienced developers.

Getting Started with Jest

Before we dive into examples, let's set up Jest in your project. If you haven't already, you can install it using npm:

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

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

"scripts": {
  "test": "jest"
}
Enter fullscreen mode Exit fullscreen mode

Now you're ready to write some tests!
Let's create a simple function to test. Create a file named math.js:

// math.js
function add(a, b) {
  return a + b;
}
module.exports = add;
Enter fullscreen mode Exit fullscreen mode

Now, let's write a test for this function. Create a file named math.test.js:

// math.test.js
const add = require('./math');

test('adds 1 + 2 to equal 3', () => {
  expect(add(1, 2)).toBe(3);
});
Enter fullscreen mode Exit fullscreen mode

In this test, we use the test function to define a test case. The expect function is used to assert that the result of add(1, 2) is equal to 3.

Running the Tests

You can run your tests by executing the following command in your terminal:

npm test
Enter fullscreen mode Exit fullscreen mode

You should see output indicating that your test has passed.

Testing Asynchronous Code

Jest also supports testing asynchronous code. Let's modify our math.js file to include an asynchronous function:

// math.js
function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('peanut butter');
    }, 1000);
  });
}

module.exports = { add, fetchData };
Enter fullscreen mode Exit fullscreen mode

Now, let's write a test for fetchData:

// math.test.js
const { add, fetchData } = require('./math');

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

test('fetches data', async () => {
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});
Enter fullscreen mode Exit fullscreen mode

In this test, we mark the test function as async and use await to wait for the promise to resolve.

Mocking Functions

Jest provides powerful mocking capabilities. Let's say you have a function that makes an API call. You can mock this function to control its behavior during tests.
Here's an example:

// api.js
const axios = require('axios');

async function getUser() {
  const response = await axios.get('https://api.example.com/user');
  return response.data;
}

module.exports = getUser;
Enter fullscreen mode Exit fullscreen mode

You can mock axios in your test:

// api.test.js
const axios = require('axios');
const getUser = require('./api');

jest.mock('axios');

test('fetches user data', async () => {
  const user = { name: 'John Doe' };
  axios.get.mockResolvedValue({ data: user });

  const result = await getUser();
  expect(result).toEqual(user);
});
Enter fullscreen mode Exit fullscreen mode

In this test, we mock the axios.get method to return a predefined response, allowing us to test getUser without making an actual API call.

Jest is a powerful testing framework that makes it easy to write and run tests for your JavaScript applications. With its simple syntax, support for asynchronous code, and built-in mocking capabilities, Jest can help you ensure your code is reliable and maintainable. Start integrating Jest into your projects today, and enjoy the benefits of automated testing.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.