Is it possible to set event.isTrusted to true in JEST unit tests?

Viewed 1114

I am working with JavaScript events. As per the following MDN article, the event object has a flag called isTrusted. https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted

I have written a code which differentiates user events (triggered as a result of an actual user action) from programmatic events (triggered as a result of element.dispatchEvent(...). I cannot show the entire code but it goes something like below:

document.addEventListener('click', (event) => {
  if (event.isTrusted) {
    // ... client code follows
    // somewhere in the code I am dispatching another custom event on body element
    document.body.dispatchEvent(...);
  }
});

I am trying to unit test this code in JEST (a popular unit testing library). Unfortunately we cannot simulate real click events since it's an automated code that does it for you. The the flag isTrusted is always set to false in JEST, thereby restricting me to test the client code.

I cannot change the value of isTrusted directly since it is a read only property. I am looking for ways where I can mock the event and set the isTrusted flag to true.


Edit: Added the test code:


describe('Event.isTrusted', () => {
  beforeAll(() => {
    document.body.dispatchEvent = jest.fn();
    const btn = document.createElement('button');
    btn.id = 'btn';
    document.body.appendChild(btn);
  });
  ...
  it('should allow user events', () => {
    const event = new MouseEvent('click', {
      bubbles: true,
      cancellable: true
    });
    document.getElementById('btn').dispatchEvent(event);
    expect(document.body.dispatchEvent).toHaveBeenCalled();
  });
});

Once again this is just a gist. I cannot show the client code. I hope this helps.

1 Answers

It is possible!

describe('Event.isTrusted', () => {

  class CustomMouseEvent {
    isTrusted = true;
    // add the bubbles and cancellation here if needed
  }

  beforeAll(() => {
    Object.defineProperty(global, 'MouseEvent', {
       value: CustomMouseEvent,
    });

    document.body.dispatchEvent = jest.fn();
    const btn = document.createElement('button');
    btn.id = 'btn';
    document.body.appendChild(btn);
  });
  ...
  it('should allow user events', () => {
    const event = new CustomMouseEvent();
    document.getElementById('btn').dispatchEvent(event);
    expect(document.body.dispatchEvent).toHaveBeenCalled();
  });
});
Related