Jest React:如何mock componentDidMount绑定的window事件监听测试handleBeforeUnload
报错原因
- 你直接从
wrapper上取handleBeforeUnload是拿不到的,enzyme的shallow包装对象需要调用.instance()方法才能拿到组件的原始实例,进而访问实例方法。 handleBeforeUnload本身是组件的普通方法,不是Jest的mock或spy函数,不能直接用toHaveBeenCalled这个匹配器做调用断言。
修复后的测试代码
it('should call handleBeforeUnload', () => { const historyMock = { listen: jest.fn(), replace: jest.fn() }; const map = {}; window.addEventListener = jest.fn((event, cb) => { map[event] = cb; }); const wrapper = shallow( <AppRoutes history={historyMock} getDctkConfig={getDctkConfig} />, ); // 给组件实例的handleBeforeUnload创建监听spy const unloadSpy = jest.spyOn(wrapper.instance(), 'handleBeforeUnload'); // 触发beforeunload事件 map.beforeunload(); // 断言方法被调用 expect(unloadSpy).toHaveBeenCalled(); // 测试后清理mock,避免影响其他用例 unloadSpy.mockRestore(); window.addEventListener.mockRestore(); });
额外注意
如果你的项目使用的是React 18+且组件已经改造成函数组件,无法直接通过instance访问内部方法,可以将handleBeforeUnload逻辑抽离到组件外部,或者通过测试方法触发后的行为(比如状态变化、其他关联函数调用)做间接断言。
内容的提问来源于stack exchange,提问作者Saket Kumar
相关产品推荐
相关产品推荐

