【问题标题】:Test always passing with Sinon and Chai与诗乃和柴一起测试总是通过
【发布时间】:2017-03-30 22:35:02
【问题描述】:

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

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

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

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

我错过了什么?

【问题讨论】:

  • 我应该补充一下,这与测试更改状态无关。我一直在用另一个替换一个并拆除沙箱。

标签: node.js mocha.js sinon chai


【解决方案1】:

如果我忘记调用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 接口可以容忍无意义的标识符。

【讨论】:

  • 谢谢,整理好了!由于期望语句中的拼写错误,我不确定我认为通过测试是什么。
  • 是的,这是个问题。我经常使用 Chai,但我从不使用 should 接口,并且很少使用 expect 接口。当我为已经使用它的第三方代码贡献代码时,我会使用它。对于我自己的代码,我使用assert 接口。它不会尝试对属性做任何魔术,因此如果使用错误的方法名称,它会hard失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多