3

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?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
user2613341
  • 53
  • 1
  • 1
  • 4
  • Does this answer your question? [How can I mock the JavaScript window object using Jest?](https://stackoverflow.com/questions/41885841/how-can-i-mock-the-javascript-window-object-using-jest) – Liam Feb 07 '22 at 13:52

1 Answers1

10

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

Naren
  • 4,152
  • 3
  • 17
  • 28