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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…