Search code examples
javascriptunit-testingsinon

Sinon spy callCount returns 0


I can't seem to get my test working. I have a simple mixin like so:

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

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

And a simple test as well:

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/

It logs did it but the spy's callCount value is 0. If I do const spy = sinon.spy(console, 'log');, the spy's callCount is 1. What's the correct way of spying for instance methods?


Solution

  • I used TestElement.prototype for spying and also moved it before instantiating new TestElement();. It now works but can someone explain why?

    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/