我是mocha / sinon / promises的新手。我在模拟函数上写了一个函数,它返回一个承诺让我很困惑。我在下面创建了一个完整的例子,在这一点上有点做作,因为我试图将其剥离到显示问题的最低限度。
'use strict';
const sinon = require('sinon');
var _fakeGetAndPost = {
get: (cmd, cb) => cb("", cmd),
post: (cmd, cb) => cb("", cmd)
};
function getCardsFromList(specificGetCardsCmd) {
return new Promise((resolve, reject) => {
_fakeGetAndPost.get(specificGetCardsCmd, (err, response) => {
if (err) {
reject(err);
} else {
resolve(response);
}
});
});
}
describe("Experiment with mock", () => {
it("The mock passes with both once() and never() - but shouldn't", () => {
var myMock = sinon.mock(_fakeGetAndPost);
myMock.expects('get').once(); //never() also passes, /twice() fails
getCardsFromList("junk");
myMock.verify();
myMock.restore();
});
});
混淆来自myMock.expects('get').once();
行。如果我将once()
的期望替换为twice()
,则测试会按预期失败。但是,如果我将once()
替换为never()
代码仍会传递。我对此感到惊讶,并且不明白这是怎么发生的。如果twice()
也已经过去,我会怀疑摩卡不等待承诺但是由于twice()
失败,看起来这种机制起作用了。