Here's a beginner-friendly Node.js Jest Tutorial to get you started with testing in Node.js using Jest.
Jest is a popular JavaScript testing framework often used for React, but it works just as well for testing Node.js applications.
It provides an easy-to-use syntax, built-in assertions, and mock functionality, making it a great choice for testing.
1. Setting Up a Node.js Project with Jest
Let's start from the beginning by setting up a basic Node.js project with Jest.
Step 1: Initialize the Node.js Project
Open your terminal and navigate to the folder where you want your project.
mkdir nodejs-jest-tutorial
cd nodejs-jest-tutorial
npm init -y
This creates a new package.json file in your project folder.
Step 2: Install Jest
Next, install Jest as a development dependency.
npm install --save-dev jest
Step 3: Add a Test Script
Open the package.json file and modify the scripts section to add a test command that runs Jest.
"scripts": {
"test": "jest"
}
2. Write a Simple Node.js Function
Let's write a simple Node.js function to test. Create a new file called math.js:
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
const divide = (a, b) => b !== 0 ? a / b : 'Cannot divide by zero';
module.exports = { add, subtract, multiply, divide };
In this file, we have simple functions to add, subtract, multiply, and divide numbers.
3. Create Test File
Now, we’ll write Jest tests for this math.js file. Create a math.test.js file in the same directory:
// math.test.js
const { add, subtract, multiply, divide } = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
test('subtracts 5 - 3 to equal 2', () => {
expect(subtract(5, 3)).toBe(2);
});
test('multiplies 3 * 3 to equal 9', () => {
expect(multiply(3, 3)).toBe(9);
});
test('divides 6 / 2 to equal 3', () => {
expect(divide(6, 2)).toBe(3);
});
test('divide by zero returns error message', () => {
expect(divide(6, 0)).toBe('Cannot divide by zero');
});
Here, we have five tests, one for each operation in math.js. We're using Jest's expect() and toBe() functions to assert that the results are correct.
4. Run the Tests
Now, you can run the tests using the following command:
npm test
Jest will automatically find all the files with .test.js in the name and run them. You should see output similar to this:
> nodejs-jest-tutorial@1.0.0 test
> jest
PASS ./math.test.js
✓ adds 1 + 2 to equal 3 (3 ms)
✓ subtracts 5 - 3 to equal 2
✓ multiplies 3 * 3 to equal 9
✓ divides 6 / 2 to equal 3
✓ divide by zero returns error message
Test Suites: 1 passed, 1 total
Tests: 5 passed, 5 total
If all tests pass, you're ready to start writing more tests for your Node.js project!
5. Mocking Functions with Jest
Jest also provides a powerful mocking functionality. Let's say you want to test a function that calls an external API or interacts with a database. You can mock those functions.
Here's an example of how to mock a function.
Example: Mocking an HTTP request
Let's say you have a function that fetches data from an API:
// fetchData.js
const fetchData = (url) => {
return fetch(url)
.then(response => response.json())
.catch(error => console.error('Error:', error));
};
module.exports = fetchData;
You can test this function by mocking the fetch function, like so:
// fetchData.test.js
const fetchData = require('./fetchData');
// Mocking the global fetch function
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data: 'sample data' }),
})
);
test('fetches data successfully', async () => {
const result = await fetchData('https://api.example.com/data');
expect(result.data).toBe('sample data');
expect(fetch).toHaveBeenCalledWith('https://api.example.com/data');
});
In this example, fetch is mocked to return a Promise with the data we expect, and the test checks that fetchData correctly handles the data.
6. Using Jest for Async Tests
Jest supports async tests using async/await, and it also supports Promises and callback-based tests.
Here's an example of testing a function that returns a promise:
// asyncFunction.js
const fetchDataAsync = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Async data'), 1000);
});
};
module.exports = fetchDataAsync;
Now test it:
// asyncFunction.test.js
const fetchDataAsync = require('./asyncFunction');
test('fetchDataAsync returns async data', async () => {
const data = await fetchDataAsync();
expect(data).toBe('Async data');
});
7. Coverage Reporting
Jest also has a built-in coverage reporter. You can run tests with coverage to see which lines of your code are being tested and which aren't:
npm test -- --coverage
This will output a coverage report in the terminal, showing you what percentage of your code is covered by tests.
8. Summary
In this tutorial, you learned how to:
- Set up Jest in a Node.js project.
- Write basic tests for functions.
- Test synchronous and asynchronous code.
- Mock functions and external dependencies.
- Generate a code coverage report.
Jest is a powerful tool, and this tutorial just scratches the surface.
You can explore more advanced features like snapshots, custom matchers, and integration tests as you grow more comfortable with Jest.
Feel free to explore Jest's official documentation for more advanced topics:
https://jestjs.io/docs/en/getting-started
Good luck with your testing! 🚀