1

How do I test that a CustomEvent is dispatched in jasmine? When I try running the following code I get the error: "ReferenceError: Can't find variable: CustomEvent".

function testCustomEvent() {
  window.dispatchEvent(new CustomEvent('myCustomEvent', {
    detail: 'foo'
  }));
}

describe('testCustomEvent', function() {
  it('dispatches myCustomEvent', function() {
    var eventSpy = jasmine.createSpy();
    window.addEventListener('myCustomEvent', eventSpy);

    testCustomEvent();

    expect(eventSpy).toHaveBeenCalledWith('foo');
  });
});
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
wwwuser
  • 6,282
  • 8
  • 52
  • 64

2 Answers2

2

The expectation is not met because eventSpy is called with { detail: 'foo'}

Also, the arguments passed is a new event object containing values of the parameter sent to the Event constructor. So it's never the same object. You will have to enforce a deep partial equal by using a partial matcher if you're using Jasmine 2.0

expect(eventSpy).toHaveBeenCalledWith(jasmine.objectContaining({
    detail: 'foo'
  }));

Or have a headache if you're using a version below 2.0

Kirill Slatin
  • 6,085
  • 3
  • 18
  • 38
0

I think the only problem with your code is:

You are using toHaveBeenCalledWith method instead of toHaveBeenCalled.

Former is used for checking two things:

  1. Expected Method is called
  2. Expected Method is called with correct arguments

Try to run your code here - Try Jasmine. After replacing toHaveBeenCalledWith with toHaveBeenCalled.

Note, do not pass any argument to latter.

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • This seems to work successfully in tryjasmine.com. However, when I use https://github.com/gruntjs/grunt-contrib-jasmine (v0.9.0) I still see the same error - "ReferenceError: Can't find variable: CustomEvent". – wwwuser Jul 13 '15 at 23:43