Ben*_*son 2 javascript dom reactjs jestjs enzyme
我有一个静态方法来创建自定义事件并分派它:
class MyComponent extends {
static refreshComponent() {
const event = new Event('refreshComponent');
document.dispatchEvent(event);
}
render() {
MyComponent.refreshComponent();
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试如下测试:
describe('refreshComponent', () => {
it('should dispatch an event', () => {
const document = { dispatchEvent: jest.fn() };
wrapper.refreshGoalsComponent();
expect(document.dispatchEvent).toHaveBeenCalledWith('refreshComponent');
});
});
Run Code Online (Sandbox Code Playgroud)
但这里没有调用dispatchEvent,因为没有“new Event()”的模拟。有办法嘲笑它吗?请帮忙
它看起来有点笨重,但是如果您想验证已调度预期的事件,类似这样的事情应该可以工作type:
describe('refreshComponent', () => {
it('should dispatch an event', () => {
const dispatchEventSpy = jest.spyOn(document, 'dispatchEvent');
// Trigger component render here...
expect(dispatchEventSpy).toHaveBeenCalledWith(expect.any(Event));
expect(dispatchEventSpy.mock.calls[0][0].type).toBe('refreshComponent');
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18456 次 |
| 最近记录: |