environment.js 4.22 KB
Newer Older
1
/* eslint-disable import/no-commonjs, max-classes-per-file */
2

3
const path = require('path');
Lukas Eipert's avatar
Lukas Eipert committed
4
const JSDOMEnvironment = require('jest-environment-jsdom');
5
const { ErrorWithStack } = require('jest-util');
6 7 8 9
const {
  setGlobalDateToFakeDate,
  setGlobalDateToRealDate,
} = require('./__helpers__/fake_date/fake_date');
10
const { TEST_HOST } = require('./__helpers__/test_constants');
11

12 13
const ROOT_PATH = path.resolve(__dirname, '../..');

14 15
class CustomEnvironment extends JSDOMEnvironment {
  constructor(config, context) {
16 17
    // Setup testURL so that window.location is setup properly
    super({ ...config, testURL: TEST_HOST }, context);
Winnie Hellmann's avatar
Winnie Hellmann committed
18

19 20 21
    // Fake the `Date` for `jsdom` which fixes things like document.cookie
    // https://gitlab.com/gitlab-org/gitlab/-/merge_requests/39496#note_503084332
    setGlobalDateToFakeDate();
22

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
    Object.assign(context.console, {
      error(...args) {
        throw new ErrorWithStack(
          `Unexpected call of console.error() with:\n\n${args.join(', ')}`,
          this.error,
        );
      },

      warn(...args) {
        throw new ErrorWithStack(
          `Unexpected call of console.warn() with:\n\n${args.join(', ')}`,
          this.warn,
        );
      },
    });
Winnie Hellmann's avatar
Winnie Hellmann committed
38 39

    const { testEnvironmentOptions } = config;
40
    const { IS_EE } = testEnvironmentOptions;
Winnie Hellmann's avatar
Winnie Hellmann committed
41
    this.global.gon = {
42
      ee: IS_EE,
Winnie Hellmann's avatar
Winnie Hellmann committed
43
    };
44
    this.global.IS_EE = IS_EE;
45

46 47 48
    // Set up global `gl` object
    this.global.gl = {};

49 50
    this.rejectedPromises = [];

51
    this.global.promiseRejectionHandler = (error) => {
52 53
      this.rejectedPromises.push(error);
    };
54

55
    this.global.fixturesBasePath = `${ROOT_PATH}/tmp/tests/frontend/fixtures${IS_EE ? '-ee' : ''}`;
56
    this.global.staticFixturesBasePath = `${ROOT_PATH}/spec/frontend/fixtures`;
57

58 59 60 61 62 63
    /**
     * window.fetch() is required by the apollo-upload-client library otherwise
     * a ReferenceError is generated: https://github.com/jaydenseric/apollo-upload-client/issues/100
     */
    this.global.fetch = () => {};

64
    // Expose the jsdom (created in super class) to the global so that we can call reconfigure({ url: '' }) to properly set `window.location`
65
    this.global.jsdom = this.dom;
66 67 68 69 70 71

    Object.assign(this.global.performance, {
      mark: () => null,
      measure: () => null,
      getEntriesByName: () => [],
    });
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    //
    // Monaco-related environment variables
    //
    this.global.MonacoEnvironment = { globalAPI: true };
    Object.defineProperty(this.global, 'matchMedia', {
      writable: true,
      value: (query) => ({
        matches: false,
        media: query,
        onchange: null,
        addListener: () => null, // deprecated
        removeListener: () => null, // deprecated
        addEventListener: () => null,
        removeEventListener: () => null,
        dispatchEvent: () => null,
      }),
    });

91 92 93 94 95 96 97
    /**
     * JSDom doesn't have an own observer implementation, so this a Noop Observer.
     * If you are testing functionality, related to observers, have a look at __helpers__/mock_dom_observer.js
     *
     * JSDom actually implements a _proper_ MutationObserver, so no need to mock it!
     */
    class NoopObserver {
98 99 100 101
      /* eslint-disable no-useless-constructor, no-unused-vars, no-empty-function, class-methods-use-this */
      constructor(callback) {}
      disconnect() {}
      observe(element, initObject) {}
102 103 104 105
      unobserve(element) {}
      takeRecords() {
        return [];
      }
106
      /* eslint-enable no-useless-constructor, no-unused-vars, no-empty-function, class-methods-use-this */
107 108 109 110 111 112 113 114 115 116
    }

    ['IntersectionObserver', 'PerformanceObserver', 'ResizeObserver'].forEach((observer) => {
      if (this.global[observer]) {
        throw new Error(
          `We overwrite an existing Observer in jsdom (${observer}), are you sure you want to do that?`,
        );
      }
      this.global[observer] = NoopObserver;
    });
117 118 119
  }

  async teardown() {
120 121 122
    // Reset `Date` so that Jest can report timing accurately *roll eyes*...
    setGlobalDateToRealDate();

123 124 125 126 127 128 129 130 131 132
    await new Promise(setImmediate);

    if (this.rejectedPromises.length > 0) {
      throw new ErrorWithStack(
        `Unhandled Promise rejections: ${this.rejectedPromises.join(', ')}`,
        this.teardown,
      );
    }

    await super.teardown();
133 134 135 136
  }
}

module.exports = CustomEnvironment;