grunt testing api with supertest, express and mocha

白昼怎懂夜的黑 提交于 2019-12-04 13:04:25

When using superagent, you should always pass it an Express application which has been configured (middleware registered, controllers routed, etc.)--but not initialized as a HTTP server. It will do that for you and it will defer, through http.createServer, to the OS to pick an available port.

If you currently have that the server.js module is already providing a static instance of a full-blown HTTP server, that is most likely the source of your problems. In either case, try extracting the application configuration/bootstrapping from the actual server instantiation like so:

// server.js
var express = require('express');
var middleware = require('./middleware');
var controllers = require('./controllers');

// Configures the Express application instance.
exports.setup = function (app) {
    app.use(middleware.foo);
    app.get('/bar', controllers.bar);

    app.locals.baz = 'quux';
}

// You might shoot yourself in the foot if parts of your application depend
// on a static reference at `server.app`.
exports.app = setup(express());
exports.app.listen(3000);

Then, in your tests, you can do something along the lines:

// tests.js
var express = require('express');
var server = require('./server');

describe('Server tests', function () {
    // Create a fresh server instance prior to each test
    beforeEach(function createNewSever() {
        this.app = server.setup(express());
    });

    describe('Foo', function () {
        it('barrs', function () {
            request(this.app)  // initializes a server instance on port A
            // ... supertests
        });

        it('bazzes', function () {
            request(this.app)  // initializes a server instance on port B
            // ... more supertests
        });
    });
});

This is just for illustrative purposes, where the when/how of instantiating the application instance will depend on your test context. The important thing to take away is that you should be able to create fresh, clean, independent and isolated server instances for your test cases. It is an absolute necessity should you use a test runner that executes tests in parallel or in a random order.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!