I'm trying to mock window.location in my tests. I have a file that exports certain configs based on window.location so I need to test if it is returning the correct configs based on the window location. I was first trying to set a testURL in jest config but from what I can see online, that this is not supported in create-react-app. So then I tried to go this route of mocking window location.
import config from 'src/config';
// this just returns an object with configs
delete global.window.location;
global.window.location = {
ancestorOrigins: null,
hash: null,
host: 'test-app.com',
port: '80',
protocol: 'http',
hostname: 'test-app.com',
href: 'http://test-app.com',
origin: 'http://test-app.com',
pathname: null,
search: null,
assign: null,
reload: null,
replace: null
}
console.log(window.location) //logs the above so I can see it changes
describe('Configuration', () => {
it('Loads correct config', () => {
expect(config.serviceEnv.toEqual({...}));
// if I add a console.log here it keeps returning the values relative to localhost,
// meaning it does not change. Also, if I add a console log to the config file it does not
// log the mock location
})
})
Config.js
const { hostname } = window.location;
// adding a console log here keeps showing me default values instead of
// mock location and so in the test when I assert on the value returned
// it fails
let serviceEnv;
if (hostname.indexOf('dev') > -1) {
serviceEnv = 'dev'
} else if (hostname.indexOf('qa') > -1)
serviceEnv = 'qa'
} else {
serviceEnv = 'dev'
}
}
}
export default {
..someotherConfigs,
serviceEnv
}
Any ideas how can I test this? Appreciate any guidance, thanks!
Revision 1: Based on the post shared by Xiduzo in the comments I have changed the test to the following but still the location inside config file does not use the mocked location
describe('Configuration', () => {
let windowSpy;
beforeEach(() => {
windowSpy = jest.spyOn(window, 'window', 'get')
})
afterEach(() => {
windowSpy.mockRestore();
})
it('Loads correct config', () => {
windowSpy.mockImplementation(() => ({
location: {
ancestorOrigins: null,
hash: null,
host: 'dummy.com',
port: '80',
protocol: 'http',
hostname: 'test-app.com',
href: 'http://test-app.com',
origin: 'http://test-app.com',
pathname: null,
search: null,
assign: null,
reload: null,
replace: null
}
})
console.log(config)
// still shows default config from else condition meaning it does not use the mock location data
})
})