1
const request = require('supertest');

const server = request('http://localhost:9001');

describe('Get /static/component-list.json', function() {
    const api = server.get('/static/component-list.json');

    it('should response a json', function(done) {
        api.expect('Content-Type', /json/, done);
    });
    it('200', function(done) {
        api.expect(200, done); // This will failed
        // server.get('/static/component-list.json').expect(200, done); // This will successed
    });
});

api在第二个测试用例中重用时,mocha 将引发错误:

命令结果mocha test/api

摩卡错误

如何请求一次 url 并在多种it情况下使用。

4

1 回答 1

3

解决方案

it您必须为要运行的每个测试(每个)创建一个新请求。您不能对多个测试重复使用相同的请求。所以

describe('Get /static/component-list.json', function() {
    let api;

    beforeEach(() => {
        api = server.get('/static/component-list.json');
    });

或者,如果您想减少发出的请求数量,请将您对请求的所有检查合并到一个 Mocha 测试中。

解释

如果您查看 的代码supertest,您会发现当您调用expect带有回调的方法时,expect调用会自动调用end. 所以这:

api.expect('Content-Type', /json/, done);

相当于:

api.expect('Content-Type', /json/).end(done);

end方法由 提供superagentsupertest用于执行请求。该end方法是启动请求的原因。这意味着您已经完成了请求的设置并希望现在将其关闭。

end方法调用request方法,该方法的任务是使用 Node 的网络机制来生成用于执行网络操作的 Node 请求对象。问题是request缓存了 Node 请求,但是这个 Node 请求对象是不可重用的。所以最终,一个superagentorsupertest请求不能被结束两次。您必须为每个测试重新发出请求。

(您可以通过执行手动刷新测试之间的缓存对象api.req = undefined但我强烈建议不要这样做。一方面,您可能认为您会得到的任何优化都是最小的,因为仍然必须重新发出网络请求。其次,这个数量搞乱superagent的内部结构。它可能会在未来的版本中中断。第三,可能还有其他保持状态的变量可能需要与 一起重置req。)

于 2016-06-02T11:39:58.830 回答