总是通过 Sinon 和 Chai 的测试

Test always passing with Sinon and Chai

我正在使用 Mocha、Chai 和 Sinon 来测试一些 Node 方法。

此测试通过,当我将 'calledOnce' 更改为 'calledTwice' 时,它按预期失败了。

 it('should call checkIfRoomExists once', function (done) {
            var check = sandbox.spy(RoomInfoModel, 'checkIfRoomExists');
            ViewBusiness.getViewToRender("thisisanoneknownroom", function (viewName) {
                expect(check.calledOnce).to.equal(true);
                done();
            })
        });

然而,当我尝试按照教程进行操作时,'expect' 是这样设置的:

it('should call checkIfRoomExists once', function (done) {
        var check = sandbox.spy(RoomInfoModel, 'checkIfRoomExists');
        ViewBusiness.getViewToRender("thisisanoneknownroom", function (viewName) {
            expect(check).to.have.been.calledTwice;
            done();
        })
    });

请注意,我在第二次测试中测试 'calledTwice'。它仍然通过。如果我将其更改为 'notCalled',它仍然会通过。基本上它总是通过。

我错过了什么?

我可以重现您报告的行为的唯一方法是,如果我忘记调用 chai.use 将 Sinon 的断言添加到其中。例如,这按预期工作(测试失败):

const sinon = require("sinon");
const chai = require("chai");
const sinonChai = require("sinon-chai");
chai.use(sinonChai); // This is crucial to get Sinon's assertions.
const expect = chai.expect;

it("test", () => {
    const stub = sinon.stub();
    stub();
    expect(stub).to.have.been.calledTwice;
});

但是如果你拿同样的代码注释掉chai.use(sinonChai),那么测试就通过了!


为了好玩,您可以尝试 expect(stub).to.have.been.platypus,那也会过去的。 Chai 的 expect 界面容忍无意义的标识符。