reactjs - 如何模拟 JavaScript window.open 和 window.clo

我的代码的 PFB 快照。

const childWindow = window.open('https://example.com')
setTimeout(() => {
    childWindow.close()
}, 1000)

我无法为上述快照编写单元测试用例。

谁能给我一些想法吗?

最佳答案

您可以使用 jest.fn() 直接模拟 window.open。 This answer例子比较多,看看吧!!

jest.useFakeTimers() // Keep at the Top of the file

it('should test window.open', () => {
   const closeSpy = jest.fn()
   window.open = jest.fn().mockReturnValue({ close: closeSpy })
   window.close = jest.fn()

   // Invoke main function

   expect(window.open).toHaveBeenCalled()
   expect(window.open).toHaveBeenCalledWith('https://example.com')

   jest.runAllTimers()

   expect(closeSpy).toHaveBeenCalled()
})

关于reactjs - 如何模拟 JavaScript window.open 和 window.close?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64799458/

相关文章:

html - 将垂直对齐设置为中间不能应用于复选框

php - 元素临 : Change or remove category/tag/author p

c# - if else 语句简化以提高可读性

javascript - Alpine JS 表格数据绑定(bind)

java - spring.profiles.active 在 spring boot 应用程序中不

python - 有没有办法在 python 列表中切换元素?

perl - 可能对未定义的取消引用数组进行迭代是错误还是功能?

c# - 1053 Windows 服务错误使用 .NET Core 3.1 Worker 服务

html - React Material UI-制作一个按钮打开文件选择器窗口

c# - 是否可以在不复制的情况下为多个组件创建一个 Blazor 范围的 CSS 文件?