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
情况下使用。
您必须为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
方法由提供superagent
,supertest
用于执行请求。该end
方法是启动请求的方法。这意味着您已经完成了设置请求,并希望立即将其解雇。
该end
方法调用request
method,该方法的任务是使用Node的联网设备来生成Node请求对象,该对象用于执行网络操作。问题是request
生成了Node请求的高速缓存,但是此Node请求对象不可重用。因此,最终,一个superagent
或supertest
请求不能结束两次。您必须为每个测试重新发出请求。
(您可以通过在两次测试之间手动刷新缓存的对象api.req = undefined
。但是,我强烈建议您这样做。一方面,您可能认为可以获得的任何优化都是最小的,因为仍然需要重新提出网络请求。第二,这笔费用(superagent
可能会在将来的版本中破坏)。第三,可能还有其他保持状态的变量可能需要与req
。一起重置。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句