Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 233
user2613341 Avatar asked Oct 16 '25 06:10

user2613341


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

like image 133
Naren Avatar answered Oct 18 '25 22:10

Naren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!