Home Web Front-end JS Tutorial Unit, Integration, and ETesting in One Example Using Jest

Unit, Integration, and ETesting in One Example Using Jest

Nov 20, 2024 pm 07:53 PM

Introduction

Many developers face challenges when it comes to testing their code. Without proper tests, bugs can slip through, leading to frustrated users and costly fixes.

This article will show you how to effectively apply Unit, Integration, and End-to-End testing using Jest, Supertest, and Puppeteer on a very simple example built using Node.js and MongoDB.

By the end of this article, I hope you will have a clear understanding of how to apply these types of tests in your own projects.

?‍? Please find the full example here in this repo.

Introducing our Dependencies

Before installing our dependencies, let me introduce our example first. It is a very simple example in which a user can open the registration page, set their registration details, click the registration button, and have their information stored in the database.

In this example, we will use the following packages:

npm install --save jest express mongoose validator
npm install --save-dev jest puppeteer jest-puppeteer mongodb-memory-server supertest npm-run-all
Copy after login
Copy after login
Copy after login
Copy after login

Most of these dependencies are straightforward, but here are clarifications for a couple of them:

  • puppeteer: Allows you to control a headless browser (Chrome) for automated testing and web scraping.
  • Jest-Puppeteer: It is preset for Jest that integrates Puppeteer, simplifying the setup for running end-to-end tests in a browser environment. You can use it as a preset in the jest.config.js file and you can customize the Puppeteer behavior through a file called jest-puppeteer.config.js.
  • mongodb-memory-server: It is a utility that spins up an in-memory MongoDB instance for fast and isolated testing of database interactions.
  • npm-run-all: A CLI tool to run multiple npm scripts in parallel or sequentially.

Unit Testing

  • Definition: Unit testing focuses on testing individual components or functions in isolation. The goal is to verify that each unit of code performs as expected.
  • Speed: Unit tests are typically very fast because they test small pieces of code without relying on external systems or databases.
  • Example: In our user registration example, a unit test might check the function that validates an email address. For instance, it would verify that the function correctly identifies user@example.com as valid while rejecting user@.com or user.com.

Nice, let’s translate this into code.

Setting Up the Unit Testing Environment

To run your unit tests without unpredictable behaviors, you should reset the mock functions before every test. You can achieve this using the beforeEach hook:

// setup.unit.js

beforeEach(() => {
  jest.resetAllMocks();
  jest.restoreAllMocks();
}); 
Copy after login
Copy after login
Copy after login
Copy after login

Testing Email Validation

In this case, we want to test the validateInput function:

npm install --save jest express mongoose validator
npm install --save-dev jest puppeteer jest-puppeteer mongodb-memory-server supertest npm-run-all
Copy after login
Copy after login
Copy after login
Copy after login

It is a very simple function that validates if the provided input contains a valid email. Here is its unit test:

// setup.unit.js

beforeEach(() => {
  jest.resetAllMocks();
  jest.restoreAllMocks();
}); 
Copy after login
Copy after login
Copy after login
Copy after login

await expect(async () => {}).rejects: Based on the Jest documentation, this is the way to expect the reason for a rejected promise.

Testing for Duplicated Emails

Let’s test another function that checks if there is a duplicated email in the database. Actually, this one is interesting because we have to deal with the database, and at the same time, unit testing should not deal with external systems. So what should we do then? Well, we should use Mocks.

First, have a look at the emailShouldNotBeDuplicated function we need to test:

// register.controller.js
const validator = require('validator');

const registerController = async (input) => {
  validateInput(input);
  ...
};

const validateInput = (input) => {
  const { name, email, password } = input;
  const isValidName = !!name && validator.isLength(name, { max: 10, min: 1 });
  if (!isValidName) throw new Error('Invalid name');
  ...
};
Copy after login
Copy after login
Copy after login

As you see, this function sends a request to the database to check if there is another user having the same email. Here’s how we can mock the database call:

// __tests__/unit/register.test.js
const { registerController } = require('../controllers/register.controller');

describe('RegisterController', () => {
  describe('validateInput', () => {
    it('should throw error if email is not an email', async () => {
      const input = { name: 'test', email: 'test', password: '12345678' };
      await expect(async () => await registerController(input)).rejects.toThrow('Invalid email');
    });
  });
});
Copy after login
Copy after login

We mocked (spied) the database findOne method using jest.spyOn(object, methodName) which creates a mock function and tracks its calls. As a result, we can track the number of calls and the passed parameters of the spied findOne method using the toHaveBeenNthCalledWith.

Integration Testing

  • Definition: Integration testing evaluates how multiple components work together. It checks the interactions between different functions, modules, or services.
  • Speed: Integration tests are slower than unit tests because they involve multiple components and may require database access or network calls.
  • Example: For the user registration process, an integration test could verify that when sending the registration request, the user data is correctly validated and stored in the database. This test would ensure that all components—like the input validation, API endpoint, and database interaction—work together as intended.

Setting Up the Integration Testing Environment

Before writing our integration test, we have to configure our environment:

npm install --save jest express mongoose validator
npm install --save-dev jest puppeteer jest-puppeteer mongodb-memory-server supertest npm-run-all
Copy after login
Copy after login
Copy after login
Copy after login
  • As you see, we export the testingApp because we will need it in the integration tests. And we export it as a function because it is being exported before it is fully initialized, since beforeAll is asynchronous, the module.exports statement runs before testingApp is assigned a value, resulting in it being undefined when we try to use it in our test files.
  • By using Jest hooks, we were able to do the following:
    • beforeAll: Starts the Express server and connects to the in-memory MongoDB database.
    • afterAll: Closes the Express server and stops the running in-memory MongoDB database.
    • beforeEach: Cleans up the database by dropping the users collection before each test case.

Now, we are ready to run our integration test.

Testing the Registration API Request

Let’s test the entire server-side registration process—from sending the registration request to storing user details in the database and redirecting to the success page:

// setup.unit.js

beforeEach(() => {
  jest.resetAllMocks();
  jest.restoreAllMocks();
}); 
Copy after login
Copy after login
Copy after login
Copy after login

As you see, the registerController function integrates multiple components (functions), validateInput, emailShouldNotBeDuplicated, and createUser functions.

So, let’s write our integration test:

// register.controller.js
const validator = require('validator');

const registerController = async (input) => {
  validateInput(input);
  ...
};

const validateInput = (input) => {
  const { name, email, password } = input;
  const isValidName = !!name && validator.isLength(name, { max: 10, min: 1 });
  if (!isValidName) throw new Error('Invalid name');
  ...
};
Copy after login
Copy after login
Copy after login
  • As you see, in this test case, we use the supertest package to send a registration request to our API. This simulates real user behavior during the registration process.
  • In this case, we didn’t mock the database calls, because we need to test the real behavior.

End-to-End (E2E) Testing

  • Definition: E2E testing simulates real user scenarios to validate the entire application flow from start to finish. It tests the application as a whole, including the user interface and backend services.
  • Speed: E2E tests are the slowest among the three types because they involve navigating through the application interface and interacting with various components, often requiring multiple network requests.
  • Example: In the context of user registration, an E2E test would simulate a user opening the registration page, filling out their details (like name, email, and password), clicking the “Register” button, and then checking if they are redirected to a success page. This test verifies that every part of the registration process works seamlessly together from the user’s perspective.

Let’s jump into our example.

Setting Up the E2E Testing Environment

Actually, in our example, the environment configuration for end-to-end testing is similar to that of integration testing.

Testing Registration Process from Start to End

In this case, we need to exactly simulate real user registration behavior, from opening the registration page, filling in their details (name, email, password), clicking the “Register” button, and finally being redirected to a success page. Have a look at the code:

npm install --save jest express mongoose validator
npm install --save-dev jest puppeteer jest-puppeteer mongodb-memory-server supertest npm-run-all
Copy after login
Copy after login
Copy after login
Copy after login

Let’s break down this code:

  • There are a lot of tools you can use to implement your end-to-end testing, here we are using Jest along with Puppeteer to implement our end-to-end testing.
  • You might be wondering what is page variable? Like Jest expect, it is a global variable provided by Puppeteer, representing a single tab in a browser where we can perform actions like navigating and interacting with elements.
  • We are using Puppeteer to simulate the user behavior by opening that page using goto function, filling in the inputs using type function, clicking the registration button using click function.

Running All Tests Together with Different Configurations

Unit, Integration, and ETesting in One Example Using Jest

Photo by Nathan Dumlao on Unsplash

At this point, you might be wondering how to run all test types simultaneously when each has its own configuration. For example:

  • In unit testing, you need to reset all mocks before every test case, while in integration testing, this is not necessary.
  • In integration testing, you must set up your database connection before running your tests, but in unit testing, this is not required.

So, how can we run all the test types at the same time while ensuring that each respects its corresponding configuration?

To tackle this problem, follow these steps:

1. Let’s create three different configuration files, jest.unit.config.js:

// setup.unit.js

beforeEach(() => {
  jest.resetAllMocks();
  jest.restoreAllMocks();
}); 
Copy after login
Copy after login
Copy after login
Copy after login

jest.integration.config.js:

// register.controller.js
const validator = require('validator');

const registerController = async (input) => {
  validateInput(input);
  ...
};

const validateInput = (input) => {
  const { name, email, password } = input;
  const isValidName = !!name && validator.isLength(name, { max: 10, min: 1 });
  if (!isValidName) throw new Error('Invalid name');
  ...
};
Copy after login
Copy after login
Copy after login

jest.e2e.config.js:

// __tests__/unit/register.test.js
const { registerController } = require('../controllers/register.controller');

describe('RegisterController', () => {
  describe('validateInput', () => {
    it('should throw error if email is not an email', async () => {
      const input = { name: 'test', email: 'test', password: '12345678' };
      await expect(async () => await registerController(input)).rejects.toThrow('Invalid email');
    });
  });
});
Copy after login
Copy after login

2. Next, update your npm scripts in the package.json file as follows:

// register.controller.js
const { User } = require('../models/user');

const registerController = async (input) => {
    ...
  await emailShouldNotBeDuplicated(input.email);
  ...
};

const emailShouldNotBeDuplicated = async (email) => {
  const anotherUser = await User.findOne({ email });
  if (anotherUser) throw new Error('Duplicated email');
};
Copy after login

--config: Specifies the path to the Jest configuration file.

npm-run-all --parallel: Allows running all tests in parallel.

3. Then, create three setup files named setup.unit.js, setup.integration.js, and setup.e2e.js, containing the necessary setup code used in the previous sections.
4. Finally, run all tests by executing this command npm run test. This command will execute all unit, integration, and end-to-end tests in parallel according to their respective configurations.

Conclusion

In this article, we explored unit, integration, and end-to-end (E2E) testing, emphasizing their importance for building reliable applications. We demonstrated how to implement these testing methods using Jest, Supertest, and Puppeteer in a simple user registration example with Node.js and MongoDB.

In fact, a solid testing strategy not only improves code quality but also boosts developer confidence and enhances user satisfaction.

I hope this article has provided you with useful insights that you can apply to your own projects. Happy testing!

Think about it

If you found this article useful, check out these articles as well:

  • MongoDB GridFS Made simple
  • How I Improved Video Streaming with FFmpeg and Node.js
  • 4 Ways To Handle Asynchronous JavaScript

Thanks a lot for staying with me up till this point. I hope you enjoy reading this article.

The above is the detailed content of Unit, Integration, and ETesting in One Example Using Jest. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles