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

use*_*341 3 reactjs jestjs enzyme

我的代码的 PFB 快照。

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

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

谁能给我一些想法吗?

Nar*_*ren 11

您可以使用直接模拟 window.open jest.fn()这个答案有更多例子,看看吧!

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()
})

Run Code Online (Sandbox Code Playgroud)