dav*_*ell 13 javascript jestjs
我在尝试测试某个 CustomEvent 是否已在类中调度时收到误报。我正在用来jest.spyOn测试通过调用传递的特定 CustomEvent dispatchEvent。这是调度自定义事件的函数:
someFunction() {
this.dispatchEvent(
new CustomEvent('myEvent', {
bubbles: true,
composed: true,
detail: { someProperty: this.localProperty },
})
);
}
Run Code Online (Sandbox Code Playgroud)
测试尝试以这种方式验证预期事件:
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);
});
Run Code Online (Sandbox Code Playgroud)
lis*_*tdm 16
如果您在 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" },
}));
Run Code Online (Sandbox Code Playgroud)
就我而言,两者的结果都是: { isTrusted: [Getter] }
这就是为什么这不会失败的原因:
expect(dispatchEventSpy).toHaveBeenCalledWith(customEvent);
Run Code Online (Sandbox Code Playgroud)
您可以使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17697 次 |
| 最近记录: |