首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sinon存根函数参数

Sinon存根函数参数
EN

Stack Overflow用户
提问于 2019-12-04 17:41:12
回答 1查看 488关注 0票数 1

我有一个带有路由器的express应用程序,我想用Sinon测试一下。我不能成功地模拟传递给请求处理程序的response参数,因此需要一些帮助。

代码语言:javascript
复制
export const pingHandler = (request, response, next) => {
    response.status(200).send('Hello world');
}

这是我目前使用Mocha,Sinon,Chai & sinon-chai的测试设置。fakeRes.status从未像预期的那样被调用。

代码语言:javascript
复制
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
    });
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-04 18:02:09

以下是单元测试解决方案:

index.ts

代码语言:javascript
复制
export const pingHandler = (request, response, next) => {
  response.status(200).send('Hello world');
}

index.spec.ts

代码语言:javascript
复制
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%覆盖率的单元测试结果:

代码语言:javascript
复制
 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 |                   |
---------------|----------|----------|----------|----------|-------------------|
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59172920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档