我在网上搜索过,但我没有找到在react测试库甚至jest中模拟window.close()的方法。
const handleClose = () => {
window.opener.location.reload()
window.close()
}
<Button
data-test-id="close"
onClick={handleClose}
/>如何实现button和window.close()和window.opener.location.reload()的onclick的测试用例覆盖率
我的测试用例如下
const wrapper = render( <CloseButton />);
const windowSpy = jest.spyOn(global, 'window', 'get');
const { queryByTestId } = wrapper;
fireEvent.click(queryByTestId('close');
expect(windowSpy.opener.location.relaod).toHaveBeenCalled();
expect(windowSpy.close).toHaveBeenCalled(); 对于这最后一行代码'expect(windowSpy.close).toHaveBeenCalled();‘,我得到一个错误,说“接收的值必须是模拟或间谍函数。接收的值未定义”。
对于expect(windowSpy.opener.location.relaod).toHaveBeenCalled();//,它显示未定义windowSpy.opener。
请来人帮帮忙!
发布于 2020-09-28 04:13:41
你只是在模仿window,但是你没有提供任何实现。
这应该会有帮助:
windowSpy.mockImplementation(() => ({
close: jest.fn(),
opener: {
location: {
reload: jest.fn(),
}
}
}));https://stackoverflow.com/questions/64092855
复制相似问题