Sinon间谍callCount返回0

时间:2019-05-28 05:40:26

标签: javascript unit-testing sinon

我似乎无法通过测试。我有一个像这样的简单mixin:

export const mixin = superclass => class mixin extends superclass {
  constructor() {
    super();
    this.addEventListener('do-it', this.doIt);
  }

  doIt() {
    console.log('did it');
  }
};

还有一个简单的测试:

describe('mixin', () => {
  it('should call doIt', () => {
    class TestElement extends mixin(HTMLElement) {}
    customElements.define('test-element', TestElement);

    const el = new TestElement();
    const spy = sinon.spy(el, 'doIt');

    el.dispatchEvent(new CustomEvent('do-it'));

    expect(spy.callCount).to.equal(1);
  });
});

https://jsfiddle.net/nbuLhvkd/

它记录did it,但间谍的callCount值为0。如果我做const spy = sinon.spy(console, 'log');,则间谍的callCount1。监视实例方法的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

您的'dispatchEvent'调用很可能是异步的,因此callCount确实为0,因为它是同步执行的。 否则,您的语法就很好-证明了您对控制台调用的测试。

答案 1 :(得分:0)

我使用TestElement.prototype进行监视,并在实例化new TestElement();之前也将其移动了。现在可以使用,但是有人可以解释原因吗?

describe('Sinon examples', () => {
  it('logs test on do-it', () => {
    class TestElement extends mixin(HTMLElement) {}
    customElements.define('test-element', TestElement);

    const spy = sinon.spy(TestElement.prototype, 'doIt');
    const el = new TestElement();

    el.dispatchEvent(new CustomEvent('do-it'));

    expect(spy.calledOnce).to.be.true;
  });
});

https://jsfiddle.net/h0f9Le16/

相关问题