2020-06-16 12:09:00 +00:00
|
|
|
/**
|
|
|
|
* Manage the instance of a custom `window.location`
|
|
|
|
*
|
|
|
|
* This only encapsulates the setup / teardown logic so that it can easily be
|
2021-09-15 12:11:13 +00:00
|
|
|
* reused with different implementations (i.e. a spy or a fake)
|
2020-06-16 12:09:00 +00:00
|
|
|
*
|
|
|
|
* @param {() => any} fn Function that returns the object to use for window.location
|
|
|
|
*/
|
2020-12-23 21:10:24 +00:00
|
|
|
const useMockLocation = (fn) => {
|
2020-06-16 12:09:00 +00:00
|
|
|
const origWindowLocation = window.location;
|
2021-08-05 06:09:25 +00:00
|
|
|
let currentWindowLocation = origWindowLocation;
|
2020-06-16 12:09:00 +00:00
|
|
|
|
|
|
|
Object.defineProperty(window, 'location', {
|
|
|
|
get: () => currentWindowLocation,
|
|
|
|
});
|
|
|
|
|
|
|
|
beforeEach(() => {
|
|
|
|
currentWindowLocation = fn();
|
|
|
|
});
|
|
|
|
|
|
|
|
afterEach(() => {
|
|
|
|
currentWindowLocation = origWindowLocation;
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create an object with the location interface but `jest.fn()` implementations.
|
|
|
|
*/
|
|
|
|
export const createWindowLocationSpy = () => {
|
|
|
|
return {
|
|
|
|
assign: jest.fn(),
|
|
|
|
reload: jest.fn(),
|
|
|
|
replace: jest.fn(),
|
|
|
|
toString: jest.fn(),
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Before each test, overwrite `window.location` with a spy implementation.
|
|
|
|
*/
|
|
|
|
export const useMockLocationHelper = () => useMockLocation(createWindowLocationSpy);
|