-
Notifications
You must be signed in to change notification settings - Fork 0
/
jest.setupTests.js
161 lines (137 loc) · 4.43 KB
/
jest.setupTests.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
const { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } = require('fs');
const crypto = require('crypto');
const { extname, join, resolve } = require('path');
const packageJson = require('./package.json');
jest.mock('child_process', () => ({
...jest.requireActual('child_process'),
execSync: (...args) => `<execSync>${JSON.stringify(args)}</execSync>`
}));
/**
* Note: Mock the packages export and avoid Jest module loading issues.
* At least 1 of the packages we're exporting creates an issue for Jest.
*/
jest.mock('./lib/packages', () => ({
babelLoaderResolve: 'babel-loader',
babelPresetEnvResolve: '@babel/preset-env',
cssLoaderResolve: 'css-loader',
tsLoaderResolve: 'ts-loader'
}));
/**
* A testing and development checked in fixture path
*
* @type {string}
*/
global.fixturePath = resolve(__dirname, '__fixtures__');
/**
* A testing and development temporary fixture path
*
* @type {string}
*/
global.tempFixturePath = resolve(__dirname, '.fixtures');
/**
* Clean up a fixture
*
* @param {string} file
* @param {object} options
* @param {boolean} options.useExistingFixturePaths Including a file+path set this to false
*/
const removeFixture = (file, { useExistingFixturePaths = true } = {}) => {
const tempFixture = (useExistingFixturePaths && join(tempFixturePath, file)) || file;
const fixture = (useExistingFixturePaths && join(fixturePath, file)) || file;
if (existsSync(tempFixture)) {
rmSync(tempFixture);
} else if (existsSync(fixture)) {
rmSync(fixture);
}
};
global.removeFixture = removeFixture;
/**
* Generate a fixture from string literals.
*
* @param {string} contents
* @param {object} options
* @param {string} options.dir
* @param {string} options.ext
* @param {string} options.encoding
* @param {string} options.filename
* @param {boolean} options.resetDir
* @returns {{path: string, file: string, contents: *, dir: string}}
*/
const generateFixture = (
contents,
{ dir = tempFixturePath, ext = '.txt', encoding = 'utf8', filename, resetDir = true } = {}
) => {
const updatedFileName = filename || crypto.createHash('md5').update(contents).digest('hex');
const file = extname(updatedFileName) ? updatedFileName : `${updatedFileName}${ext}`;
const path = resolve(dir, file);
if (resetDir && existsSync(dir)) {
rmSync(dir, { recursive: true });
}
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
writeFileSync(path, contents, { encoding });
const updatedContents = readFileSync(path, { encoding });
return { dir, file, path, contents: updatedContents, removeFixture: (p = file) => removeFixture(p) };
};
global.generateFixture = generateFixture;
/**
* Generate a mock for snapshot display
*
* @param {Array} mockFunctions
* @returns {{}}
*/
const setMockResourceFunctions = mockFunctions => {
const setupMock =
mock =>
(...args) =>
`<${mock}>${JSON.stringify(args)}</${mock}>`;
const mocks = {};
mockFunctions.forEach(mock => {
mocks[mock] = setupMock(mock);
});
return mocks;
};
global.setMockResourceFunctions = setMockResourceFunctions;
/**
* Shallow mock specific properties, restore with callback, mockClear.
* A simple object property mock for scenarios where the property is not a function/Jest fails.
*
* @param {object} object
* @param {object} propertiesValues
* @returns {{mockClear: Function}}
*/
const mockObjectProperty = (object = {}, propertiesValues) => {
const updatedObject = object;
const originalPropertiesValues = {};
Object.entries(propertiesValues).forEach(([key, value]) => {
originalPropertiesValues[key] = updatedObject[key];
updatedObject[key] = value;
});
return {
mockClear: () => {
Object.assign(updatedObject, originalPropertiesValues);
}
};
};
global.mockObjectProperty = mockObjectProperty;
/**
* Provide a consistent way of processing configs.
*
* @param {*} value
* @param {object} options
* @param {boolean} options.isHash
* @param {string} options.projectName
* @returns {string}
*/
const cleanConfigurationPaths = (value, { isHash = false, projectName = packageJson.name } = {}) => {
const contents = JSON.stringify([(typeof value === 'function' && value.toString()) || value], null, 2).replace(
new RegExp(`"[a-z0-9/-_.,*()\\s]*\\/${projectName}\\/`, 'gi'),
'"./'
);
if (isHash) {
return crypto.createHash('md5').update(contents).digest('hex');
}
return contents;
};
global.cleanConfigurationPaths = cleanConfigurationPaths;