gpt4 book ai didi

javascript - spy 无法跟踪 Mocha 和 Sinon 的异步功能测试

转载 作者:行者123 更新时间:2023-11-29 15:30:33 27 4
gpt4 key购买 nike

我有如下的 isMember 函数;

function isMember(req, res, next) {
MyService.GetUserAsync(authCookie)
.then(function (user) {
next();
})
.catch(function (err) {
if (err.status === 400) {
return res.redirect("/notAllowed");
}
else {
return next(err);
}
});
}

我的测试如下;

 beforeEach(function () {        
// Overwrite the global timer functions (setTimeout, setInterval) with Sinon fakes
this.clock = sinon.useFakeTimers();
});
afterEach(function () {
// Restore the global timer functions to their native implementations
this.clock.restore();
});

it.only("pass authentication and set authCookie", function (done) {
var user = {
userNameField: "fakeUserName"
};
sinon.stub(MyService, "GetUserAsync").returns(Promise.resolve(user));
var spyCallback = sinon.spy();
var req {};
var res = {};
isMember(req, res, spyCallback);
// Not waiting here!
this.clock.tick(1510);
// spyCallback.called is always false
expect(spyCallback.called).to.equal(true);
done();
});

出于某种原因,this.clock.tick 无法正常工作,并且 spyCallback.called 始终为 false。我怎样才能让我的 spy 等到 next() 在 isMember 函数中被调用?

最佳答案

sinon fakeTimers 替换全局 setTimeout 函数,但您的代码不包含任何超时函数。

您可以使用 setTimeout 函数来延迟期望的执行,然后通过在 setTimeout 中调用 done() 来解决您的测试。你可以尝试这样的事情:

setTimeout(function () {
expect(spyCallback.called).to.equal(true);
done();
}, 0);

关于javascript - spy 无法跟踪 Mocha 和 Sinon 的异步功能测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35345475/

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