javascript - 使用 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);
});
解决方案
如果你在 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);
推荐阅读
- docker - minio presigned 获取 url 403 SignatureDoesNotMatch
- java - JavaFX Button 防止收缩
- powershell - 为什么这个 powershell .Replace() 不起作用?
- entity-framework-core - EF Core 2.2 - StartsWith 在两个不同的列上
- swift - Firebase Realtime DB - 从数组中获取特定数据?
- google-cloud-platform - 无法在 Google Cloud Tasks 上设置 Payload/Body
- python - 如果视图来自不同的 URL,如何以不同的方式执行视图?
- sql - 多个参数不是强制性的
- r - 基于公式的 NPV 计算:卡住创建序列
- html - 在 ng-repeat 中根据 $index 拆分 div 背景颜色