测试总是通过Sinon和Chai

时间:2016-11-16 16:15:58

标签: node.js mocha sinon chai

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

这个测试过去了,当我改变了#Once'被称为“双关语”它按预期失败了。

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

然而,当我尝试并按照教程时,期望'设置如下:

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

请注意,我正在测试“被叫”。在第二次测试中。它仍然通过。如果我将其更改为' notcalled'它仍然通过。基本上它总是通过。

我错过了什么?

1 个答案:

答案 0 :(得分:2)

我可以重现您报告的行为的唯一方法是,如果我忘记调用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接口允许无意义的标识符。