I am getting false positives trying to test that a certain CustomEvent was dispatched in a class. I am using jest.spyOn to test what specific CustomEvent was passed through the dispatchEvent call. Here is the function that dispatches a custom event:
someFunction() {
this.dispatchEvent(
new CustomEvent('myEvent', {
bubbles: true,
composed: true,
detail: { someProperty: this.localProperty },
})
);
}
And the test attempts to validate the expected event this way:
let container;
beforeEach(() => {
container = new SomeClass();
});
it('dispatches correct CustomEvent when someFunction is called', () => {
const dispatchEventSpy = jest.spyOn(container, 'dispatchEvent');
container.localProperty = '123';
const customEvent = new CustomEvent('myEvent', {
bubbles: true,
composed: true,
detail: { someProperty: 'wrong value' },
});
container.someFunction();
// TODO: I expect the below to fail because the format passed in the custom event does not match the format in the container.
expect(dispatchEventSpy).toHaveBeenCalledWith(customEvent);
// If I use toBe instead and check the argument passed to dispatchEvent this way it fails even when they are the same. So I either get a false positive or a false negative.
expect(dispatchEventSpy.mock.calls[0][0]).toBe(customEvent);
});