是否可以在 JEST 单元测试中将 event.isTrusted 设置为 true?

Sac*_*ngh 6 javascript events unit-testing readonly dom-events

我正在处理JavaScript事件。根据以下 MDN 文章,事件对象有一个名为 的标志isTrustedhttps://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted

我编写了一段代码,用于区分用户事件(由于实际用户操作而触发)和编程事件(由于 而触发)element.dispatchEvent(...)。我无法显示整个代码,但它如下所示:

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(...);
  }
});
Run Code Online (Sandbox Code Playgroud)

我正在尝试在(一个流行的单元测试库)中对这段代码进行单元测试JEST。不幸的是,我们无法模拟真实的点击事件,因为它是为您执行此操作的自动代码。在 JEST 中,该标志isTrusted始终设置为false,从而限制我测试客户端代码。

我无法直接更改 的值,isTrusted因为它是只读属性。我正在寻找可以模拟该事件并将isTrusted标志设置为 的方法true


编辑:添加测试代码:


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();
  });
});
Run Code Online (Sandbox Code Playgroud)

再说一遍,这只是一个要点。我无法显示客户端代码。我希望这有帮助。

小智 1

有可能的!

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();
  });
});
Run Code Online (Sandbox Code Playgroud)