Sinon存根函数参数

时间:2019-12-04 09:41:12

标签: javascript mocha sinon sinon-chai

我有一个带有路由器的Express App,我想与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
    });
});

1 个答案:

答案 0 :(得分:1)

这是单元测试解决方案:

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 |                   |
---------------|----------|----------|----------|----------|-------------------|