2016-11-16 67 views
1

我正在使用Mocha,Chai和Sinon测试一些Node方法。测试总是通过Sinon和Chai

此测试通过,当我将'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(); 
      }) 
     }); 

然而,当我尝试,并按照教程“期望”设置这样的:

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',它仍然会通过。基本上它总是通过。

我错过了什么?

+0

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

回答

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接口可以容忍无意义的标识符。

+0

谢谢,那已经排序了!不知道由于预期声明中的拼写错误,我认为测试通过了。 –

+0

是的,这是一个问题。我使用Chai很多,但我从不使用'should'接口,而且很少使用'expect'接口。当我为已经使用它的第三方代码贡献时使用它。对于我自己的代码,我使用'assert'接口。它不会尝试对属性做任何魔法,所以如果使用错误的方法名称,它会失败。 – Louis

相关问题