Unit testing Simple and middleware without starting a server

Is there a way to unit test the Express / Loopback middleware without actually creating the server and listening on the port?

The problem is that creating multiple servers in my test code will cause a port conflict problem.

+4
source share
1 answer

You can use the supertest module .

You can pass http.Server or a function for the request () - if the server is not yet listening for connections, then it is bound to the ephemeral port for you, so there is no need to monitor the ports.

Mocha

Mocha example

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

, 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();
      });
  });
});

serial ava it. .

loopback ( node), , . , serial, , , .

+4

Source: https://habr.com/ru/post/1658151/


All Articles