summaryrefslogtreecommitdiff
path: root/spec/frontend/mocks/mocks_helper.js
blob: 0aa803314345a0ccd099746bfdb93884cf8a4128 (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
55
56
57
58
/**
 * @module
 *
 * This module implements auto-injected manual mocks that are cleaner than Jest's approach.
 *
 * See https://docs.gitlab.com/ee/development/testing_guide/frontend_testing.html
 */

import fs from 'fs';
import path from 'path';

import readdir from 'readdir-enhanced';

const MAX_DEPTH = 20;
const prefixMap = [
  // E.g. the mock ce/foo/bar maps to require path ~/foo/bar
  { mocksRoot: 'ce', requirePrefix: '~' },
  // { mocksRoot: 'ee', requirePrefix: 'ee' }, // We'll deal with EE-specific mocks later
  // { mocksRoot: 'virtual', requirePrefix: '' }, // We'll deal with virtual mocks later
];

const mockFileFilter = stats => stats.isFile() && stats.path.endsWith('.js');

const getMockFiles = root => readdir.sync(root, { deep: MAX_DEPTH, filter: mockFileFilter });

// Function that performs setting a mock. This has to be overridden by the unit test, because
// jest.setMock can't be overwritten across files.
// Use require() because jest.setMock expects the CommonJS exports object
const defaultSetMock = (srcPath, mockPath) =>
  jest.mock(srcPath, () => jest.requireActual(mockPath));

export const setupManualMocks = function setupManualMocks(setMock = defaultSetMock) {
  prefixMap.forEach(({ mocksRoot, requirePrefix }) => {
    const mocksRootAbsolute = path.join(__dirname, mocksRoot);
    if (!fs.existsSync(mocksRootAbsolute)) {
      return;
    }

    getMockFiles(path.join(__dirname, mocksRoot)).forEach(mockPath => {
      const mockPathNoExt = mockPath.substring(0, mockPath.length - path.extname(mockPath).length);
      const sourcePath = path.join(requirePrefix, mockPathNoExt);
      const mockPathRelative = `./${path.join(mocksRoot, mockPathNoExt)}`;

      try {
        setMock(sourcePath, mockPathRelative);
      } catch (e) {
        if (e.message.includes('Could not locate module')) {
          // The corresponding mocked module doesn't exist. Raise a better error.
          // Eventualy, we may support virtual mocks (mocks whose path doesn't directly correspond
          // to a module, like with the `ee_else_ce` prefix).
          throw new Error(
            `A manual mock was defined for module ${sourcePath}, but the module doesn't exist!`,
          );
        }
      }
    });
  });
};