简体   繁体   English

在不启动服务器的情况下对Express / Loopback中间件进行单元测试

[英]Unit testing Express / Loopback middleware without starting a server

Is there a way to unit test Express / Loopback middleware without actually creating a server and listening on a port? 有没有办法在不实际创建服务器和监听端口的情况下对Express / Loopback中间件进行单元测试?

The problem I have is that creating multiple servers in my test code will introduce the problem of port conflicts. 我遇到的问题是在我的测试代码中创建多个服务器会引入端口冲突的问题。

You can use the supertest module. 您可以使用超级模块。

You may pass an http.Server, or a Function to request() - if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports. 您可以将http.Server或函数传递给request() - 如果服务器尚未侦听连接,则它会绑定到临时端口,因此无需跟踪端口。

Mocha 摩卡

An example with mocha mocha的一个例子

var request = require('supertest');
var app = require('path/to/server.js');

describe('GET /user', function() {
  it('respond with json', function(done) {
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

Ava 艾娃

Also, you might be interested in the ava test runner instead of mocha. 此外,您可能对ava测试运行器而不是mocha感兴趣。

Main reason : process isolation between test files 主要原因测试文件之间的进程隔离

This is usually my test file template with ava 这通常是我的ava测试文件模板

var describe = require('ava-spec').describe;
var app = require('path/to/server.js');
var request = require('supertest');

describe("REST API", function(it){
  it.before.cb(function(t){
    request(app)
      .post('/api/Clients/')
      .send({
        "username": "foo",
        "password": "bar"
      })
      .expect(200, function(err, res){
          t.end(err);
      });
  });

  it.serial.cb('Does something',
  function(t){
    request(app)
      .get(//..)
      .expect(404, function(err, res){
        if (err) return t.end(err);
        t.end();
      });
  });
  it.serial.cb('Does something else afterward',
  function(t){
    request(app)
      .get(//..)
      .expect(401, function(err, res){
        if (err) return t.end(err);
        t.end();
      });
  });
});

The serial identifier tells ava to run the it clause serially. serial标识符告诉ava serial运行it子句。 Otherwise it will run all tests from all files in parallel. 否则,它将并行运行所有文件中的所有测试。

Thanks to process isolation, each test file gets its own, isolated loopback instance (and node environment in general), and all test files can be run in parallel, which speeds up tests as well. 由于进程隔离,每个测试文件都有自己独立的环回实例(通常是节点环境),并且所有测试文件都可以并行运行,这也加快了测试速度。 Inside each test file however, using serial , tests will run one after another, in the order they are written in the file. 但是,在每个测试文件中,使用serial ,测试将按照它们在文件中写入的顺序一个接一个地运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM