【发布时间】:2021-02-24 04:40:44
【问题描述】:
我的代码的 PFB 快照。
const childWindow = window.open('https://example.com')
setTimeout(() => {
childWindow.close()
}, 1000)
我无法为上述快照编写单元测试用例。
谁能给我一些想法?
【问题讨论】:
我的代码的 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()
})
【讨论】:
jest.resetAllMocks()