Supertest:发送后无法设置标头

时间:2016-04-18 05:32:16

标签: node.js express supertest

表达和猫鼬。

为了测试我正在使用supertest,mocha和mockgoose。

当我尝试为两次连续测试设置auth令牌时,第二次测试失败了Can't set headers after they are sent.

测试用例如下所示。

var chai = require('chai'),
    expect = chai.expect,
    server = null, 
    request = require('supertest'),
    mockgoose = require('mockgoose'),
    mongoose = require('mongoose');

describe('Organization', () => {

    var token = 'success_token',
        orgName = 'default_org_name',
        users,
        organization;

    before((done) => {
        mockgoose(mongoose);
        server = request(require('../../server/server.js'));
    });

    it('should get list of organizations for a proper user', (done) => {

        server
            .get('/api/organization/')
            .set({token : token})
            .expect(200)
            .end((err, res) => {
                if (err) return done(err);
                expect(res.body.length).to.equal(1);
                expect(res.body[0].name).to.equal(orgName);
                done();
            });

    });

    it('should send a 500 response for a incorrect user', (done) => {

        var errorToken = 'error token';

        server
            .get('/api/organization/')
            .set({token : errorToken})
            .expect(500)
            .end((err, res) => {
                if (err) return done(err);
                done();
            });

    });

    after((done) => {
        mockgoose.reset();
        done();
    });


});

第一个测试用例通过,但第二个测试用例失败。 它会抛出错误

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
    at ServerResponse.header (/home/tricon/aniket/dev/publab/triconpublish_api/node_modules/express/lib/response.js:718:10)
    at ServerResponse.send (/home/tricon/aniket/dev/publab/triconpublish_api/node_modules/express/lib/response.js:163:12)
    at ServerResponse.json (/home/tricon/aniket/dev/publab/triconpublish_api/node_modules/express/lib/response.js:249:15)
    at ServerResponse.send (/home/tricon/aniket/dev/publab/triconpublish_api/node_modules/express/lib/response.js:151:21)
    at /home/tricon/aniket/dev/publab/triconpublish_api/server/filter.js:9:1744
    at Query.<anonymous> (/home/tricon/aniket/dev/publab/triconpublish_api/node_modules/mongoose/lib/query.js:2169:28)
    at /home/tricon/aniket/dev/publab/triconpublish_api/node_modules/kareem/index.js:177:19
    at /home/tricon/aniket/dev/publab/triconpublish_api/node_modules/kareem/index.js:109:16
    at _combinedTickCallback (node.js:370:9)
    at process._tickDomainCallback (node.js:425:11)

我不明白这个理由。

您可以注意到我正在设置两个不同的令牌。一个用于成功场景,另一个用于错误场景。如果我在第二个测试用例中设置了相同的成功令牌,则不会抛出此错误。

请帮助!!!

1 个答案:

答案 0 :(得分:1)

我认为您需要将之前的函数调用更改为beforeEach调用。这将在每次测试之前将服务器重置为已知的基本状态。目前它正在第一次测试之前运行。

这个SO answer讨论节点的serverResponse对象。这应该可以帮助您确保在每次测试运行之前设置服务器。