Welcome to mirror list, hosted at ThFree Co, Russian Federation.

mock_window_location_helper.js « __helpers__ « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: de1e8c99b5468a0fbdbd3c71d54e9081104c21b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
 * Manage the instance of a custom `window.location`
 *
 * This only encapsulates the setup / teardown logic so that it can easily be
 * reused with different implementations (i.e. a spy or a fake)
 *
 * @param {() => any} fn Function that returns the object to use for window.location
 */
const useMockLocation = (fn) => {
  const origWindowLocation = window.location;
  let currentWindowLocation = origWindowLocation;

  Object.defineProperty(window, 'location', {
    get: () => currentWindowLocation,
  });

  beforeEach(() => {
    currentWindowLocation = fn();
  });

  afterEach(() => {
    currentWindowLocation = origWindowLocation;
  });

  return () => {
    beforeEach(() => {
      currentWindowLocation = origWindowLocation;
    });
  };
};

/**
 * Create an object with the location interface but `jest.fn()` implementations.
 */
export const createWindowLocationSpy = () => {
  const { origin, href } = window.location;

  const mockLocation = {
    assign: jest.fn(),
    reload: jest.fn(),
    replace: jest.fn(),
    toString: jest.fn(),
    origin,
    // TODO: Do we need to update `origin` if `href` is changed?
    href,
  };

  return mockLocation;
};

/**
 * Before each test, overwrite `window.location` with a spy implementation.
 */
export const useMockLocationHelper = () => useMockLocation(createWindowLocationSpy);