Jest with Node.js

beginner
7 min

Jest with Node.js

Welcome to our comprehensive guide on using Jest with Node.js! This tutorial is designed to help both beginners and intermediates understand and apply the powerful testing framework, Jest, in a Node.js environment.

Let's start by understanding why we need Jest. Testing is an essential part of software development that helps ensure our code works as expected. Jest offers easy-to-write tests, instant feedback, and a sleek interface, making it a popular choice for Node.js projects.

Introduction to Jest

Jest is a JavaScript testing framework developed by Facebook. It's designed to work seamlessly with React, but its flexibility makes it an excellent choice for testing Node.js applications too.

Installing Jest

To get started, you'll need to install Jest in your Node.js project. You can do this by running the following command in your terminal:

bash
npm install --save-dev jest

šŸ“ Note: Remember, --save-dev is used to save the package as a development dependency.

Writing Your First Test

Now that Jest is installed, let's write our first test. Create a new file named addition.js with the following content:

javascript
// addition.js function add(a, b) { return a + b; } module.exports = { add: add, };

Next, create a test file for this module called addition.test.js:

javascript
// addition.test.js const { add } = require('./addition'); test('adds two numbers', () => { expect(add(2, 3)).toBe(5); expect(add(-2, 3)).toBe(1); });

In this example, we're testing the add function from our addition.js module. The test function takes a descriptive string (the test name) and a callback function containing the actual test logic.

Running the Test

To run the test, you can use the following command in your terminal:

bash
npm test

If everything is set up correctly, Jest will execute the test and display the results.

šŸŽÆ Pro Tip: You can run tests in 'watch mode' by using the --watch flag: npm test --watch. This will automatically re-run tests whenever files change.

Writing Advanced Tests

In addition to simple tests, Jest allows for more complex scenarios. Let's create another example that demonstrates mocking and spies.

First, create a new file math.js:

javascript
// math.js const add = (a, b) => a + b; const subtract = (a, b) => a - b; const multiply = (a, b) => a * b; const divide = (a, b) => a / b; module.exports = { add, subtract, multiply, divide, };

Next, create a test file for this module called math.test.js:

javascript
// math.test.js const { add, subtract, multiply, divide } = require('./math'); const { spyOn } = require('jest-mock'; test('add function should call add function', () => { const addSpy = spyOn(Math, 'add'); add(2, 3); expect(addSpy).toHaveBeenCalledTimes(1); }); test('subtract function should call subtract function', () => { const subtractSpy = spyOn(Math, 'subtract'); subtract(4, 2); expect(subtractSpy).toHaveBeenCalledTimes(1); }); // Mock a function to test its behavior test('multiply function should return the expected result', () => { const multiplyMock = jest.fn(() => 5); const result = multiply(2, 3); expect(multiplyMock).toHaveBeenCalledTimes(1); expect(result).toBe(5); });

In this example, we're using Jest's spyOn function to monitor the calls made to built-in JavaScript functions (Math.add, Math.subtract) and our custom functions (multiply). We're also demonstrating how to mock a function for testing purposes.

Running Advanced Tests

To run these advanced tests, you can use the same npm test command. Jest will execute all tests found in the current directory and its subdirectories.

Summary

In this tutorial, we've covered the basics of Jest and explored how to write tests for Node.js applications. We've learned how to install Jest, write tests, run tests, and even touched on more advanced topics like mocking and spies.

Now, let's see how much you've learned with our quiz!

Quick Quiz
Question 1 of 1

Which command is used to install Jest as a development dependency?

Happy testing, and keep learning! šŸ¤–šŸ“ššŸš€