【问题标题】:Mock window.close() in React-testing-library在 React-testing-library 中模拟 window.close()
【发布时间】:2021-01-13 11:39:28
【问题描述】:

我在网上搜索过,但我没有找到在反应测试库甚至开玩笑中模拟 window.close() 的方法。

const handleClose = () => {
window.opener.location.reload()
window.close()
}


<Button
  data-test-id="close"
  onClick={handleClose}
/>

如何实现按钮和 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();' 我收到一条错误消息,提示“接收到的值必须是模拟或间谍函数。接收到的值未定义”

对于期望(windowSpy.opener.location.relaod).toHaveBeenCalled(); // 它说 windowSpy.opener 没有定义。

请人帮忙!!!

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme react-testing-library


    【解决方案1】:

    你只是在模拟窗口,但你没有提供任何实现。

    这应该会有所帮助:

    windowSpy.mockImplementation(() => ({
      close: jest.fn(),
      opener: {
          location: {
              reload: jest.fn(),
          }
      }
    }));
    

    【讨论】:

    • @Axnyff- 我如何模拟 window.opener.location.reload 因为在这种情况下它说 window.opener 没有定义
    • 你能在 close 属性旁边添加那个对象吗?
    猜你喜欢
    • 2020-05-26
    • 2019-10-30
    • 2021-07-16
    • 2020-05-09
    • 2023-03-24
    • 2023-03-17
    • 2020-08-01
    • 2021-01-24
    • 2022-08-06
    相关资源
    最近更新 更多