1 | export default class Location {
|
2 | private isUsingMockLocation = false;
|
3 | private assignSpy?: jest.SpyInstance;
|
4 | private reloadSpy?: jest.SpyInstance;
|
5 | private replaceSpy?: jest.SpyInstance;
|
6 |
|
7 | mock() {
|
8 | if (this.isUsingMockLocation) {
|
9 | throw new Error(
|
10 | 'You tried to mock window.location when it was already mocked.',
|
11 | );
|
12 | }
|
13 |
|
14 |
|
15 |
|
16 | Reflect.defineProperty(window.location, 'search', {
|
17 | writable: true,
|
18 | value: '',
|
19 | });
|
20 |
|
21 | this.assignSpy = jest.spyOn(window.location, 'assign');
|
22 | this.reloadSpy = jest.spyOn(window.location, 'reload');
|
23 | this.replaceSpy = jest.spyOn(window.location, 'replace');
|
24 | this.isUsingMockLocation = true;
|
25 | }
|
26 |
|
27 | restore() {
|
28 | if (!this.isUsingMockLocation) {
|
29 | throw new Error(
|
30 | 'You tried to restore window.location when it was already restored.',
|
31 | );
|
32 | }
|
33 |
|
34 | location.search = '';
|
35 | this.assignSpy!.mockRestore();
|
36 | this.reloadSpy!.mockRestore();
|
37 | this.replaceSpy!.mockRestore();
|
38 | this.isUsingMockLocation = false;
|
39 | }
|
40 |
|
41 | isMocked() {
|
42 | return this.isUsingMockLocation;
|
43 | }
|
44 | }
|