Search code examples
javascripttestingpolymermocha.jsweb-component-tester

checking that an event fired with mocha


How can I test that an element fired an event with mocha? I've got an ugly solution working, but it's not very readable, takes a long time to time out when it fails, and doesn't give good failure messaging.

describe('test-element', function() {
  var el;

  beforeEach(function() {
    el = document.createElement('test-element');
  });

  it('fires a save event', function(done) {
    el.addEventListener('save', function() {
      done();
    });
    el.save();
  });

In a perfect world, I think something like this would be cooler.

  it('fires a save event', function() {
    el.save();
    expect(el).to.have.firedEvent('save');
  });
});

Am I going about this the right way? Is there a better approach or a custom matcher library I should be using?


Solution

  • How about spying on the fire function...?

    Not sure what stubbing/spying library you're using but lets say Sinon.JS. So something like...

    var spy = sinon.spy(el, 'fire');
    el.save();
    expect(spy.calledWith('save')).to.be.true;