我有一个带有路由器的express应用程序,我想用Sinon测试一下。我不能成功地模拟传递给请求处理程序的response参数,因此需要一些帮助。
export const pingHandler = (request, response, next) => {
response.status(200).send('Hello world');
}这是我目前使用Mocha,Sinon,Chai & sinon-chai的测试设置。fakeRes.status从未像预期的那样被调用。
describe("pingHandler", () => {
it("should return 200", async () => {
const fakeResponse = {
status: sinon.fake(() => ({
send: sinon.spy()
}))
};
pingHandler({}, fakeResponse, {});
expect(fakeResponse.status).to.have.been.called;
// => expected fake to have been called at least once, but it was never called
});
});发布于 2019-12-04 18:02:09
以下是单元测试解决方案:
index.ts
export const pingHandler = (request, response, next) => {
response.status(200).send('Hello world');
}index.spec.ts
import { pingHandler } from "./";
import sinon from "sinon";
describe("pingHandler", () => {
it("should return 200", () => {
const mRes = {
status: sinon.stub().returnsThis(),
send: sinon.stub(),
};
pingHandler({}, mRes, {});
sinon.assert.calledWith(mRes.status, 200);
sinon.assert.calledWith(mRes.send, "Hello world");
});
});100%覆盖率的单元测试结果:
pingHandler
✓ should return 200
1 passing (8ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.spec.ts | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|https://stackoverflow.com/questions/59172920
复制相似问题