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

标签 javascript jestjs

我在尝试测试某个 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/

相关文章:

javascript - 有没有办法获取WebSocket请求的响应头?

javascript - 为什么使用 popcorn.js 不显示 XML 字幕?

javascript - 如何用js或jquery中的样式替换[文本] "[shortcodes]"

javascript - React - 在功能组件中测试外部功能

unit-testing - 在 Jest 中模拟模块时如何断言调用默认导出函数?

javascript - 曲奇饼。 CORS。如果我提交表单而不使用preventDefault(),浏览器不会设置cookie;

javascript - 更改 window.resize 上的变量值

angular - 如何使用 jasmine-karna 以 Angular 对嵌套函数进行单元测试

node.js - 使用 Nodejs 和 Supertest 进行子域集成测试

vue.js - vue + Jest + typescript : Unexpected token = at class static function