【问题标题】:Sinon stub function parameterSinon 存根函数参数
【发布时间】:2020-03-29 01:45:00
【问题描述】:

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

【问题讨论】:

    标签: javascript mocha.js sinon sinon-chai


    【解决方案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 |                   |
    ---------------|----------|----------|----------|----------|-------------------|
    

    【讨论】:

    • 哇,绝妙的答案!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2015-02-12
    • 2021-02-20
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多