gpt4 book ai didi

javascript - Sinon stub 函数参数

转载 作者:行者123 更新时间:2023-12-02 22:22:48 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com