So in order to avoid this, we use wrappers which are easier to mock:
const defineGlobalWindow = (locationValue?: string) => {
global.window = Object.create(window);
const url = locationValue || "spTestHost";
Object.defineProperty(window, "location", {
value: { hostname: url },
writable: true
});
};
import wrappers from 'utils/wrappers';
export default const getConfig = () => {
if(wrappers.getLocation() === LOCALHOST) {
// do something in localhost
}
...
}
const getLocation = () => window.location;
export default {
getLocation
};
import wrappers from './wrappers';
const defaultWrappers = {
...wrappers
};
export default {
wrappers,
mock(key, mock) {
wrappers[key] = mock
},
restore(key) {
wrappers[key] = defaultWrappers[key];
}
};
import wrappersMock from 'utils/wrappers-mock';
afterEach(() => wrappersMock.restore('getLocation'));
it('config do something when in localhost', () => {
wrappersMock.mock('getLocation', () => 'http://localhost');
const result = getConfig();
expect(result).toBe(something);
});