Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65935065/is-it-possible-to-set-event-istrusted-to-true-in-jest-unit-tests

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...