Jest is a popular testing framework for JavaScript applications, including Node.js. It is widely used for unit testing, and it comes with built-in support for mocking, assertions, and test runners. Here's a basic guide on how to use Jest for unit testing in Node.js:
Installation: First, you need to install Jest in your Node.js project. You can do this using npm:
bashnpm install --save-dev jest
Jest will automatically be added to your devDependencies
in your package.json
file.
Create a Test File:
Create a test file in the same directory as your code, with a .test.js
or .spec.js
extension. For example, if your main file is app.js
, create a test file named app.test.js
.
Write a Test:
In your test file, use the test
function provided by Jest to define your test cases. Here's a simple example:
javascript// app.js
function add(a, b) {
return a + b;
}
// app.test.js
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
Run Tests: To run your tests, you can use the following command:
bashnpx jest
Alternatively, you can add a script to your package.json
file for easier execution:
json{
"scripts": {
"test": "jest"
}
}
Then you can run your tests using:
bashnpm test
Assertions:
Jest provides a variety of assertion functions to check values. The expect
function is a key part of this. For example:
javascript// app.test.js
test('checks if a value is greater than 5', () => {
expect(10).toBeGreaterThan(5);
});
Mocking:
Jest simplifies mocking. You can use jest.mock
to mock dependencies. For example:
javascript// app.js
const fetchData = () => {
// Some asynchronous operation
};
module.exports = fetchData;
javascript// app.test.js
jest.mock('./app'); // Assuming app.js is in the same directory
const fetchData = require('./app');
test('fetchData is called', () => {
fetchData();
expect(fetchData).toHaveBeenCalled();
});
This is a basic overview to get you started. Jest offers many other features, such as setup and teardown functions (beforeEach
, afterEach
, beforeAll
, afterAll
), coverage reporting, and more. Refer to the Jest documentation for a comprehensive guide and advanced usage.