您可以使用 Sinon 的 spy 和 stub 函数来测试您的代码,如下所示:
const { spy, stub } = require('sinon');
const chai = require('chai');
chai.should();
describe('the get function', () => {
let status,
json,
res;
beforeEach(() => {
status = stub();
json = spy();
res = { json, status };
status.returns(res);
});
describe('if called with a request that has an example query', () => {
beforeEach(() => get({ query: { example: true } }, res));
it('calls status with code 200', () =>
status.calledWith(200).should.be.ok
);
it('calls json with success: true', () =>
json.calledWith({ success: true }).should.be.ok
);
});
describe('if called with a request that doesn\'t have an example query', () => {
beforeEach(() => get({ query: {} }, res));
it('calls status with code 400', () =>
status.calledWith(400).should.be.ok
);
it('calls json with error: true', () =>
json.calledWith({ error: true }).should.be.ok
);
});
});
在第一个beforeEach 调用中,我创建了一个名为status 的存根和一个名为json 的间谍。
status 存根用于测试是否使用正确的响应代码调用响应的状态方法。
json spy 用于测试响应的 json 方法是否使用正确的 JSON 代码调用。
请注意,我正在使用 status 的存根,以便能够从任何对 status 方法的调用返回模拟响应,否则链接 (res.status().json()) 将不起作用。
对于json,使用简单的间谍就足够了,因为它位于链的末端。