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