间谍无法跟踪与摩卡和西农的异步功能测试

Spy could not track on Async function test with Mocha and Sinon

本文关键字:异步 功能测试 摩卡 跟踪 间谍      更新时间:2023-09-26

我有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总是假的。如何实现我的间谍会等到next()在isMember函数中被调用?

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

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

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

你需要把done()放在回调中,因为事件循环在javascript中的工作方式。首先执行所有同步代码,然后执行所有挂起的异步任务。

摩卡支持承诺。如果您返回来自it()的承诺,它将等待。所以,你可以做一些类似的事情

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 = {};
    return isMember(req, res, spyCallback).then(function () {
        expect(spyCallback.called).to.equal(true); 
    });   
});