簡體   English   中英

使用 CustomEvent 對 dispatchEvent 進行 Jest 測試

[英]Jest testing of dispatchEvent with CustomEvent

我在嘗試測試某個 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);
});

如果你在 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);

自定義事件也可以像下面這樣測試

if (!window.CustomEvent) {
  CustomEvent = function(name, params){ return params;};
}
document.dispatchEvent = jest.fn();
expect(document.dispatchEvent.mock.calls.length).toEqual(0);
someFunction() // this is a function which is having customEvent and dispatching that event
expect(document.dispatchEvent.mock.calls.length).toEqual(1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM