


[Compilation and Sharing] Some test frameworks that can be used in Node.js
NodeWhat testing frameworks can be used? The following article will share with you some Node.js testing frameworks. I hope it will be helpful to you!
Editor's note: The author of this article is Tianzhu, an engineer at Ant Group Node.js. First, he will introduce the commonly used class libraries in each part. At the end of the article, Let’s discuss whether unit testing is necessary. Welcome to discuss it together.
Commonly used class libraries and tools
Test case executor
mocha and jest is used more often. The official new node test is still being polished, and the future is promising.
$ mocha test/egg-view-ejs.test.js render ✓ should render with locals ✓ should render with cache ✓ should render with layout ✓ should render error renderString ✓ should renderString with data ✓ should renderString error 6 passing (398ms)
Although there are so many Runners, their output standards are all in the TAP format, and then the results are output through different Reporters.
Coverage statistics
Just writing a single test is not enough. We need to know whether all the branch processes of the code are covered, so it is usually combined with code coverage. rate tool.
used to be istanbuljs, but later the author rewrote nyc. They mainly bear two responsibilities: one is to translate the code to insert the piling code, and the other is to Supports various Reporters to generate coverage reports.
Later, V8 built-in coverage statistics
, which means there is no need to translate the code anymore, and coverage data collection is natively supported.
Then this author wrote c8 focusing on generating coverage reports.
Assert class library
To verify variable results, assert is essential.
Historically appeared: expect.js, should.js, chai and power-assert, jest also has its own built-in expect.
But now the official Node.js assert/strict is actually pretty good.
Among them, power-assert is what we at EggJS have been using. I also made a good comment many years ago: "Probably the best JS Assert library - The Emperor's New Clothes".
const assert = require('power-assert'); describe('test/showcase.test.js', () => { const arr = [ 1, 2, 3 ]; it('power-assert', () => { assert(arr[1] === 10); }); }); // output: 4) test/showcase.test.js power-assert: AssertionError: # test/showcase.test.js:6 assert(arr[1] === 10) | | | | 2 false [1,2,3] [number] 10 => 10 [number] arr[1] => 2
PS: If you want to verify the file content, I have also written an assert-file, welcome to try it.
Mock & Stub Class Library
Because it is a unit test, it is often necessary to simulate the environment or downstream responses.
sinonjs Not bad, supports mock and stub, etc. jest also has its own mock library built in.
If it is an HTTP test, nock is very powerful and can help you mock the server response.
nock('http://www.example.com') .post('/login', 'username=pgte&password=123456') .reply(200, { id: '123ABC' })
However, the official Node.js undici request library also has built-in Mock capabilities.
There is also a term called snapshot, which means dumping the data during operation and directly using it as mock data for the next test, which can improve the efficiency of writing tests to a certain extent.
HTTP test class library
To test HTTP Server scenarios, the supertest library is essential.
describe('GET /users', function() { it('responds with json', async function() { return request(app) .get('/users') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then(response => { assert(response.body.email, 'foo@bar.com'); }); }); });
Command line testing library
One of the usage scenarios of Node.js is the command line CLI, such as Webpack and Babel, which themselves also need to have single tests of.
This is what we recommend:
- import { runner, KEYS } from 'clet';it('should works with boilerplate', async () => { await runner() .cwd(tmpDir, { init: true }) .spawn('npm init') .stdin(/name:/, 'example') // wait for stdout, then respond .stdin(/version:/, new Array(9).fill(KEYS.ENTER)) .stdout(/"name": "example"/) // validate stdout .notStderr(/npm ERR/) .file('package.json', { name: 'example', version: '1.0.0' }) // validate file });
Web page automated testing tool
Lightly crawl the page, you can directly use HTTP request library, recommendedundici.
To simulate the actual execution of the browser, in the early days it was Then Google officially releasedpuppeteer. Due to the accumulation of Chromium and based on the devtools-protocol protocol, it quickly became popular and killed the first two. Similar competing products include playwright and cypress.
By the way,Continuous Integration Service
When we write open source, we often need automated continuous integration services to help us test. Players in this field include:Travis, Appveyor, GitHub Actions, etc.
Now I basically use GitHub Actions, and the level of integration is so cool.Discussion: Is unit testing necessary?
There is no doubt that unit testing is very important. It is a necessary ability and professional quality of a qualified programmer. Of course, we are not 100% coverage fanatics. In many cases, we need to pursue the balance point of ROI.1. Is writing unit tests a waste of time?
First of all, let me correct a common newcomer’s point of view:Writing unit tests is a waste of time?
In fact, writing unit tests will save you time. The reason for that counter-intuitive view is that the comparison conditions are often not objective.We need to consider the cost of regression after modifying the code twice under the same quality requirements.
For a fair comparison, in addition to considering the "time for writing a single test", what is easily overlooked is the "time for regression testing after each code modification":- Writing a single test In the case of testing, create various branch mocks in the early stage, and the time for regression testing is to tap the keyboard;
- If you do not write a single test, you need to update the code into the application, and then manually simulate various Test in different situations, such as opening a browser and clicking in many different places.
It’s nothing more than the initial investment and maintenance cost. Each company has its own scale in terms of the importance it attaches to return quality and the decision-making after weighing the weight.
Of course, many of the scenarios I mentioned are framework libraries (including front-end and Node.js), server-side applications, command line tools, etc.It is true that there are some major changes Applications with front-end partial UI display or fast-up and fast-down activity pages have very high unit test maintenance costs. At this time, it is reasonable to appropriately abandon unit tests of some non-core branches based on ROI.
But we must understand that this is a last resort. We can reduce the maintenance cost of single testing through various means, but we cannot claim that unit testing is useless.
There is also a semi-automated regression test in the front-end field, which is to automate comparison based on diff, and then remind the owner to pay attention to the impact of changes. This is just like the tool libraries above, which are all here to help reduce the cost of writing single tests.
2. Shouldn’t unit tests be written by programmers?
This is also a wrong view. Unit testing should be written by programmers themselves, because it is your own code and you must be responsible for it. This is a kind of Professionalism. Any team with a little bit of standardization needs to have CI testing when submitting code, otherwise there will be no quality Code Review collaboration.
Test students are responsible for larger-level work such as integration testing, regression testing, end-to-end testing, etc.
Division of labor is different, please don’t blame others.
so...
Unit testing is very necessary. Writing unit tests is the basic professional quality of programmers. You can write as much as you can. In individual scenarios, you can ROI trade-off.
For more node-related knowledge, please visit: nodejs tutorial!
The above is the detailed content of [Compilation and Sharing] Some test frameworks that can be used in Node.js. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

npm node gyp fails because "node-gyp.js" does not match the version of "Node.js". The solution is: 1. Clear the node cache through "npm cache clean -f"; 2. Through "npm install -g n" Install the n module; 3. Install the "node v12.21.0" version through the "n v12.21.0" command.

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

How to implement OCR (optical character recognition)? The following article will introduce to you how to use node to implement OCR. I hope it will be helpful to you!
