summaryrefslogtreecommitdiff
path: root/spec/frontend/__helpers__/fixtures.js
blob: d8054d32faed5c62454d25ec72bc0ee944bea67d (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
import fs from 'fs';
import path from 'path';

import { ErrorWithStack } from 'jest-util';

export function getFixture(relativePath) {
  const basePath = relativePath.startsWith('static/')
    ? global.staticFixturesBasePath
    : global.fixturesBasePath;
  const absolutePath = path.join(basePath, relativePath);
  if (!fs.existsSync(absolutePath)) {
    throw new ErrorWithStack(
      `Fixture file ${relativePath} does not exist.

Did you run bin/rake frontend:fixtures?`,
      getFixture,
    );
  }

  return fs.readFileSync(absolutePath, 'utf8');
}

/**
 * @deprecated Use `import` to load a JSON fixture instead.
 * See https://docs.gitlab.com/ee/development/testing_guide/frontend_testing.html#use-fixtures,
 * https://gitlab.com/gitlab-org/gitlab/-/issues/339346.
 */
export const getJSONFixture = (relativePath) => JSON.parse(getFixture(relativePath));

export const resetHTMLFixture = () => {
  document.head.innerHTML = '';
  document.body.innerHTML = '';
};

export const setHTMLFixture = (htmlContent, resetHook = afterEach) => {
  document.body.innerHTML = htmlContent;
  resetHook(resetHTMLFixture);
};

export const loadHTMLFixture = (relativePath, resetHook = afterEach) => {
  const fileContent = getFixture(relativePath);
  setHTMLFixture(fileContent, resetHook);
};