gpt4 book ai didi

javascript - 使用 CustomEvent 对 dispatchEvent 进行开 Jest 测试

转载 作者:行者123 更新时间:2023-12-03 23:42:45 35 4
gpt4 key购买 nike

我在尝试测试某个 CustomEvent 是否已在某个类中分派(dispatch)时收到误报。我正在使用 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);

关于javascript - 使用 CustomEvent 对 dispatchEvent 进行开 Jest 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64784736/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com