summaryrefslogtreecommitdiff
path: root/spec/frontend/__helpers__/set_window_location_helper.js
blob: a94e73762c98355dd7f3ed5da7884af115059722 (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
/**
 * setWindowLocation allows for setting `window.location`
 * (doing so directly is causing an error in jsdom)
 *
 * Example usage:
 * assert(window.location.hash === undefined);
 * setWindowLocation('http://example.com#foo')
 * assert(window.location.hash === '#foo');
 *
 * More information:
 * https://github.com/facebook/jest/issues/890
 *
 * @param url
 */
export default function setWindowLocation(url) {
  const parsedUrl = new URL(url);

  const newLocationValue = [
    'hash',
    'host',
    'hostname',
    'href',
    'origin',
    'pathname',
    'port',
    'protocol',
    'search',
  ].reduce(
    (location, prop) => ({
      ...location,
      [prop]: parsedUrl[prop],
    }),
    {},
  );

  Object.defineProperty(window, 'location', {
    value: newLocationValue,
    writable: true,
  });
}