【问题标题】:How to mock the JavaScript window.open and window.close?如何模拟 JavaScript window.open 和 window.close?
【发布时间】:2021-02-24 04:40:44
【问题描述】:

我的代码的 PFB 快照。

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

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

谁能给我一些想法?

【问题讨论】:

标签: reactjs jestjs enzyme


【解决方案1】:

您可以使用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()
})

【讨论】:

  • 我们不需要将其重置为原始值,以便其他测试文件不使用模拟版本,除非他们明确想要吗?
  • 你可以,在 afterEach 或 afterAll 中使用jest.resetAllMocks()
猜你喜欢
  • 2014-01-21
  • 2021-01-13
  • 1970-01-01
  • 1970-01-01
  • 2010-09-19
  • 2013-09-09
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
相关资源
最近更新 更多