Sinon存根函数参数

Sinon stub function parameter

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

单元测试解决方案如下:

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