gpt4 book ai didi

javascript - sinon.mock().expects().atLeast() ...expectation.verify() 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 01:41:30 25 4
gpt4 key购买 nike

我是 Node 和 sinon 的新手,我在测试下面的组件时遇到了麻烦。我想检查 res.statusres.send 是否在组件内部被调用。

待测试组件

module.exports = {

handle: function(promise, res, next, okHttpStatus) {
promise
.then(payload => res.status(okHttpStatus ? okHttpStatus : 200).send(payload))
.catch(exception => next(exception));
}
};

单元测试

const sinon = require("sinon");
const routerPromiseHandler =
require("../../../main/node/handler/PromiseHandler");

describe("Should handle promisse", () => {

it("should handle success promise return", () => {

const successMessage = {message: "Success"};

const promiseTest = new Promise((resolve, reject) => {
resolve(successMessage);
});

let res = {
status: function() {},
send: function() {}
};

const mockRes = sinon.mock(res);
const expectStatus = mockRes.expects("status").withExactArgs(200).atLeast(1)
const expectSend = mockRes.expects("send").withExactArgs(successMessage).atLeast(1)

const spyNext = sinon.spy();

routerPromiseHandler.handle(promiseTest, res, spyNext, 200);

expectStatus.verify();
expectSend.verify();

});
});

最佳答案

我设法解决了这个问题。西农检查不起作用,因为 spy 是在 promise 中被召唤的。检查 spy 是否被召唤。我必须在 promise 的 then 和 catch 中添加断言。

const sinon = require("sinon");
const { mockResponse } = require("mock-req-res");

const routerPromiseHandler = require("../../../main/node/handler/PromiseHandler");

describe("Should handle promisse", () => {

it("should handle success promise return", () => {

const successMessage = { message: "Success" };

const promiseTest = new Promise((resolve, reject) => {
resolve(successMessage);
});

const mockedRes = mockResponse();

const spyNext = {};

routerPromiseHandler.handle(promiseTest, mockedRes, spyNext, 200);

promiseTest.then(() => {
sinon.assert.calledWithMatch(mockedRes.status, 200);
sinon.assert.calledWithMatch(mockedRes.send, successMessage);
})
});

it("should handle error promise return", () => {

const errorMessage = { error: "error" };

const promiseError = new Promise((resolve, reject) => {
reject(errorMessage);
});

const mockedRes = mockResponse();
const nextSpy = sinon.spy();

routerPromiseHandler.handle(promiseError, mockedRes, nextSpy, 200);

promiseError
.then(() => {
// Promise always need the then
})
.catch(exception => {
sinon.assert.calledWithMatch(nextSpy, errorMessage);
})
});
});

关于javascript - sinon.mock().expects().atLeast() ...expectation.verify() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742515/

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