How to mock the JavaScript window.open and window.close?

Viewed 10410

PFB snapshot of my code.

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

I am not able to write a unit test case for the above snapshot.

Can anyone please give me some ideas?

1 Answers

You can directly mock the window.open using jest.fn(). This answer has more examples, have a look at it!!

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

Related