search
HomeWeb Front-endJS Tutorial[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!

[Compilation and Sharing] Some test frameworks that can be used in Node.js

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.

[Compilation and Sharing] Some test frameworks that can be used in Node.js

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:

  • ##GitHub - node-modules/clet: Command Line E2E Testing

  • GitHub - node-modules/coffee: Test command line on Node.js

    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, recommended

undici.

To simulate the actual execution of the browser, in the early days it was

selenium and phantomjs.

Then Google officially released

puppeteer. 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,

macacajs is a multi-terminal testing tool that supports the testing of mobile APPs and desktop APPs in addition to browsers. It is open sourced by engineers from the Yuque team.

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.

[Compilation and Sharing] Some test frameworks that can be used in Node.js

[Compilation and Sharing] Some test frameworks that can be used in Node.js

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 is clear at a glance how these two take time.

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
node、nvm与npm有什么区别node、nvm与npm有什么区别Jul 04, 2022 pm 04:24 PM

node、nvm与npm的区别:1、nodejs是项目开发时所需要的代码库,nvm是nodejs版本管理工具,npm是nodejs包管理工具;2、nodejs能够使得javascript能够脱离浏览器运行,nvm能够管理nodejs和npm的版本,npm能够管理nodejs的第三方插件。

Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

node导出模块有哪两种方式node导出模块有哪两种方式Apr 22, 2022 pm 02:57 PM

node导出模块的两种方式:1、利用exports,该方法可以通过添加属性的方式导出,并且可以导出多个成员;2、利用“module.exports”,该方法可以直接通过为“module.exports”赋值的方式导出模块,只能导出单个成员。

安装node时会自动安装npm吗安装node时会自动安装npm吗Apr 27, 2022 pm 03:51 PM

安装node时会自动安装npm;npm是nodejs平台默认的包管理工具,新版本的nodejs已经集成了npm,所以npm会随同nodejs一起安装,安装完成后可以利用“npm -v”命令查看是否安装成功。

聊聊V8的内存管理与垃圾回收算法聊聊V8的内存管理与垃圾回收算法Apr 27, 2022 pm 08:44 PM

本篇文章带大家了解一下V8引擎的内存管理与垃圾回收算法,希望对大家有所帮助!

node中是否包含dom和bomnode中是否包含dom和bomJul 06, 2022 am 10:19 AM

node中没有包含dom和bom;bom是指浏览器对象模型,bom是指文档对象模型,而node中采用ecmascript进行编码,并且没有浏览器也没有文档,是JavaScript运行在后端的环境平台,因此node中没有包含dom和bom。

聊聊Node.js path模块中的常用工具函数聊聊Node.js path模块中的常用工具函数Jun 08, 2022 pm 05:37 PM

本篇文章带大家聊聊Node.js中的path模块,介绍一下path的常见使用场景、执行机制,以及常用工具函数,希望对大家有所帮助!

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),