Beginner’s Guide to Jest; Javascript Testing

SagarTS
readytowork, Inc.
Published in
3 min readSep 28, 2023

--

In the world of JavaScript development, testing is an essential practice to ensure the reliability and stability of your code. Jest, a popular JavaScript testing library, has gained widespread recognition for its simplicity, speed, and powerful features. In this article, we’ll take you on a journey through Jest, clearing its key concepts and showing you how to harness its capabilities for effective testing.

What is Jest?

Jest is an open-source JavaScript testing library created by Facebook. It is designed to make testing JavaScript applications, whether they are built with React, Node.js, or any other JavaScript framework, as easy and efficient as possible. Jest is particularly famous for its developer-friendly API and out-of-the-box configuration, making it an excellent choice for both beginners and experienced developers.

Setting Up Jest

Before we dive into writing tests, let’s set up Jest in your project. Here’s a simple step-by-step guide:

  1. Initialize Your Project: If you haven’t already, create a new JavaScript project or navigate to an existing one in your terminal.
npm init -y
or
yarn init -y

2. Install Jest: Use npm or yarn to install Jest as a development dependency.

npm install --save-dev jest
or
yarn add --dev jest

3. Create a Test Script: In your package.json, add a script for running Jest tests.

"scripts": {
...,
"test": "jest"
}

4. Write a File to Test: Create a .js file, which we will be testing with jest.

// sum.js
function sum(num1, num2) {
return num1 + num2;
}

module.exports = sum;

5. Write Your First Test: Create a test file, typically named with a .test.js extension, and write your first test.

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

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

6. Run the Tests: Execute your tests by running the following command:

npm run test
or
yarn test

If your sum function pass the test, you should see something like this in your terminal.

Writing Tests with Jest

Now that you have Jest set up, let’s explore the fundamental concepts of writing tests with Jest:

1. Test Suites and Test Cases

Jest organizes tests into “test suites” and “test cases.” Test suites group related tests, and test cases define individual test scenarios.

describe('Math operations', () => {
test('adds 1 + 2 to equal 3', () => {
// Test code here
});

test('subtracts 5 - 2 to equal 3', () => {
// Test code here
});
});

2. Expectations

Use expect() to make assertions about the behavior of your code. Jest provides various matcher functions like toBe(), toEqual(), toBeTruthy(), and more to validate your expectations.

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

3. Asynchronous Testing

For asynchronous code, Jest provides built-in support for promises and async/await.

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

const fetchData = async (id) => {
const results = await axios.get(
`https://jsonplaceholder.typicode.com/todos/${id}`
);
return results.data;
};

module.exports = fetchData;
// async.test.js
const fetchData = require('./async');

test('fetches data asynchronously', async () => {
const data = await fetchData();
expect(data).toBe('expectedData');
});

4. Mocking

Jest simplifies mocking external dependencies and functions. You can create mock functions to simulate behaviors and control the return values.

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

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

Conclusion

Jest is a powerful JavaScript testing library that simplifies the process of writing and maintaining tests for your JavaScript applications. With its straightforward setup, intuitive API, and a wide array of features, Jest is a must-have tool for any developer looking to ensure the reliability and correctness of their codebase.

In this article, we’ve covered the basics of getting started with Jest, writing test suites and cases, making assertions, mocking external dependencies, and handling asynchronous code. Armed with this knowledge, you’re well-equipped to begin testing your JavaScript projects effectively.

Start using Jest today, and watch your code quality and confidence in your applications soar to new heights!

Happy testing!

For more, you can visit this repo.

--

--