javascript - Sinon stub 函数参数

标签 javascript mocha.js sinon sinon-chai

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

关于javascript - Sinon stub 函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59172920/

相关文章:

javascript - React/Redux bundle.js 太大了

node.js - 在 Mocha 测试中监听 stdout 时“此套接字已关闭”

node.js - 测试 GraphQL API

node.js - 如何测试使用 sinon.spy 调用的 socket.io 事件

javascript - 首次使用 Mocha 和 Sinonjs 进行异步单元测试

javascript - 在 .NET 项目上生成 JSON 后期构建

javascript - 创建自动滚动 slider

javascript - $document.ready 和 $rootScope.$on ('$viewContentLoaded' 之间有什么区别)?

node.js - 如何使用 nock.js 模拟 Node-Webshot 请求?

html - 模拟 document.getElemetById ('.form' ).getContext ('2d' ) 使用 sinon