how to test a script that checks window is undefined with jest?

Viewed 253

with an imported class, i would normally just do jest.mock('foo.js') and add my implementation... but it doesn't work with the window object. even though i can properly mock it in my test, when i run the script, window is not mocked. i still want to be able to run this test in a browser env, so how would i mock the window object in my script environment vs the test environment?

below is contrived code of the current approach i have been working with...

foo.js

export default class Foo {
  validate() {
    if (window === undefined) {
      throw new Error('must be run in a browser')
    }
  }
}

foo.test.js

import Foo from 'foo.js'

it('should throw an error if not in a browser', () => {
  const foo = new Foo()
  const validateError = () => {
    foo.validate()
  }

  let windowSpy = jest.spyOn(global, 'window', 'get')
  windowSpy.mockImplementation(() => undefined)

  // this passes
  expect(window).toBeUndefined()

  // this fails
  expect(validateError).toThrow()
})
1 Answers

You can give delete global.window a try (only tested on repl.it)

const Foo = require('./Foo');

describe('Foo', () => {
  const foo = new Foo()

  describe('if there is NO global window', () => {
    beforeAll(() => {
      delete global.window
    })

    it('should throw an error', () => {
      expect(() => foo.validate()).toThrow()
    })
  })

  describe('if there IS a global window', () => {
    beforeAll(() => {
      global.window = {}
    })
    it('should not throw an error', () => {
      expect(() => foo.validate()).not.toThrow()
    })
  })
})

working example

Related