简体   繁体   中英

Test always passing with Sinon and Chai

I am using Mocha, Chai and Sinon to test some Node methods.

This test passes and when I change 'calledOnce' to 'calledTwice' it fails as expected.

 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();
            })
        });

However when I try and follow tutorials the 'expect' is set up like this:

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();
        })
    });

Note that I am testing for 'calledTwice' in the second test. It still passes. If I change it to 'notCalled' it still passes. Basically it always passes.

What am I missing?

The only way I can reproduce the behavior you report is if I forget to call chai.use to add Sinon's assertions to it. For instance, this works as expected (the test fails):

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;
});

But if you take the same code and comment out chai.use(sinonChai) , then the test will pass!


For fun, you can try expect(stub).to.have.been.platypus and that will pass too. Chai's expect interface tolerates nonsensical identifiers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM