诗乃间谍没有被召唤

时间:2017-03-21 10:29:34

标签: javascript unit-testing sinon

测试在第一次期望中失败了。有没有办法将一个间谍注入一个函数,以便我可以检查函数是否被正确的参数调用?

            var myObj = {}
            myObj.prop = function propFn () {
                return 'foo'
            }

            myObj.func = function (disp) {
                return disp(this.prop())
            }

            let disp = sinon.spy()
            sinon.stub(myObj, 'prop').callsFake(function fakeFn () {
                return 'bar'
            })

            expect(disp.called).to.be.true
            disp.should.have.been.calledWith('bar')

谢谢!

1 个答案:

答案 0 :(得分:0)

请尝试如下,

describe('prop', () => {
  const myObj = {};
  myObj.prop = function propFn() {
    return 'foo';
  };

  myObj.func = function (disp) {
    return disp(this.prop());
  };
  it('should be called', () => {
    sinon.stub(myObj, 'prop').returns('bar');
    const disp = sinon.spy();
    myObj.func(disp);
    expect(disp.callCount).to.equal(1);
    expect(myObj.prop.callCount).to.equal(1);
    expect(disp.callCount).to.equal(1);
    expect(disp.calledWith('bar')).to.equal(true);
  });
});

结果

  

     

✓应该被称为

     

1次通过(975ms)

相关问题