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
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(); });
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
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(); });
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'); ... };
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'); }); }); });
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
- 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(); });
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'); ... };
- 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
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
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(); });
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'); ... };
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'); }); }); });
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'); };
--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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version
God-level code editing software (SublimeText3)
