首页 > 解决方案 > 使用 CustomEvent 对 dispatchEvent 进行开玩笑测试

问题描述

我在尝试测试某个 CustomEvent 是否已在某个类中分派时收到误报。我jest.spyOn用来测试通过dispatchEvent调用传递了哪些特定的 CustomEvent。这是调度自定义事件的函数:

someFunction() {
    this.dispatchEvent(
        new CustomEvent('myEvent', {
            bubbles: true,
            composed: true,
            detail: { someProperty: this.localProperty },
        })
    );
}

并且测试尝试以这种方式验证预期事件:

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);
});

标签: javascriptjestjs

解决方案


如果你在 jest 单元测试中记录这个对象,你会看到结果非常相似:

console.log(new CustomEvent("myEvent", {
   bubbles: true,
   composed: true,
   detail: { someProperty: "123" },
}));
console.log(new CustomEvent("myEvent", {
  bubbles: true,
  composed: true,
  detail: { someProperty: "error" },
}));

就我而言,两者的结果都是: { isTrusted: [Getter] }

这就是为什么这不会失败:

expect(dispatchEventSpy).toHaveBeenCalledWith(customEvent);

您可以使用 dispatchEventSpy.mock.calls[0][0] 访问预期对象以获得更好的断言:

  expect(dispatchEventSpy.mock.calls[0][0].detail).toEqual({
    someProperty: "123",
  });
  expect(dispatchEventSpy.mock.calls[0][0].bubbles).toEqual(true);
  expect(dispatchEventSpy.mock.calls[0][0].composed).toEqual(true);

推荐阅读