如何模拟JavaScript window.open和window.close?

时间:2020-11-12 07:15:37

标签: reactjs jestjs enzyme

我的代码的PFB快照。

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

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

有人可以给我一些想法吗?

1 个答案:

答案 0 :(得分:2)

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