Home > Web Front-end > JS Tutorial > [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

青灯夜游
Release: 2022-08-24 19:20:25
forward
1748 people have browsed it

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)
Copy after login

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
Copy after login

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' })
Copy after login

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');
      });
  });
});
Copy after login

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!

Related labels:
source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template