forked from salesforce/lwc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhydration-tests.js
More file actions
296 lines (258 loc) · 9.68 KB
/
hydration-tests.js
File metadata and controls
296 lines (258 loc) · 9.68 KB
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
const ENGINE_SERVER = process.env.ENGINE_SERVER;
const path = require('node:path');
const vm = require('node:vm');
const fs = require('node:fs/promises');
const { format } = require('node:util');
const { rollup } = require('rollup');
const lwcRollupPlugin = require('@lwc/rollup-plugin');
const lwcSsr = ENGINE_SERVER ? require('@lwc/engine-server') : require('@lwc/ssr-runtime');
const { DISABLE_STATIC_CONTENT_OPTIMIZATION } = require('../shared/options');
const Watcher = require('./Watcher');
const context = {
LWC: lwcSsr,
moduleOutput: null,
};
lwcSsr.setHooks({
sanitizeHtmlContent(content) {
return content;
},
});
let guid = 0;
const COMPONENT_UNDER_TEST = 'main';
const TEMPLATE = `
(function (hydrateTest) {
const ssrRendered = %s;
// Component code, set as Main
%s;
// Test config, set as config
%s;
%s(%s, () => {
it('test', () => {
return hydrateTest.runTest(ssrRendered, Main, config);
})
});
})(window.HydrateTest);
`;
// Like `fs.existsSync` but async
async function exists(path) {
try {
await fs.access(path);
return true;
} catch (_err) {
return false;
}
}
async function getCompiledModule(dirName, compileForSSR) {
const bundle = await rollup({
input: path.join(dirName, 'x', COMPONENT_UNDER_TEST, `${COMPONENT_UNDER_TEST}.js`),
plugins: [
lwcRollupPlugin({
targetSSR: !!compileForSSR,
modules: [
{
dir: dirName,
},
],
experimentalDynamicComponent: {
loader: 'test-utils',
strict: true,
},
enableDynamicComponents: true,
enableLwcOn: true,
enableStaticContentOptimization: !DISABLE_STATIC_CONTENT_OPTIMIZATION,
experimentalDynamicDirective: true,
}),
],
external: ['lwc', '@lwc/ssr-runtime', 'test-utils', '@test/loader'], // @todo: add ssr modules for test-utils and @test/loader
onwarn(warning, warn) {
// Ignore warnings from our own Rollup plugin
if (warning.plugin !== 'rollup-plugin-lwc-compiler') {
warn(warning);
}
},
});
const { watchFiles } = bundle;
const { output } = await bundle.generate({
format: 'iife',
name: 'Main',
globals: {
lwc: 'LWC',
'@lwc/ssr-runtime': 'LWC',
'test-utils': 'TestUtils',
},
});
const { code } = output[0];
return { code, watchFiles };
}
function throwOnUnexpectedConsoleCalls(runnable, expectedConsoleCalls = {}) {
// The console is shared between the VM and the main realm. Here we ensure that known warnings
// are ignored and any others cause an explicit error.
const methods = ['error', 'warn', 'log', 'info'];
const originals = {};
for (const method of methods) {
originals[method] = console[method];
console[method] = function (error) {
if (
method === 'warn' &&
// This is a false positive due to RegExp.prototype.test
// eslint-disable-next-line vitest/no-conditional-tests
/Cannot set property "(inner|outer)HTML"/.test(error?.message)
) {
return;
} else if (
expectedConsoleCalls[method]?.some((matcher) => error.message.includes(matcher))
) {
return;
}
throw new Error(`Unexpected console.${method} call: ${error}`);
};
}
try {
runnable();
} finally {
Object.assign(console, originals);
}
}
/**
* This is the function that takes SSR bundle code and test config, constructs a script that will
* run in a separate JS runtime environment with its own global scope. The `context` object
* (defined at the top of this file) is passed in as the global scope for that script. The script
* runs, utilizing the `LWC` object that we've attached to the global scope, it sets a
* new value (the rendered markup) to the globalThis.moduleOutput, which correspond to
* context.moduleOutput in the hydration-test.js module scope.
*
* So, script runs, generates markup, & we get that markup out and return it to Karma for use
* in client-side tests.
*/
async function getSsrCode(moduleCode, testConfig, filename, expectedSSRConsoleCalls) {
const script = new vm.Script(
`
${testConfig};
config = config || {};
${moduleCode};
moduleOutput = LWC.renderComponent(
'x-${COMPONENT_UNDER_TEST}-${guid++}',
Main,
config.props || {},
false,
'sync'
);
`,
{ filename }
);
throwOnUnexpectedConsoleCalls(() => {
vm.createContext(context);
script.runInContext(context);
}, expectedSSRConsoleCalls);
return context.moduleOutput;
}
async function getTestModuleCode(input) {
const bundle = await rollup({
input,
external: ['lwc', 'test-utils', '@test/loader'],
});
const { watchFiles } = bundle;
const { output } = await bundle.generate({
format: 'iife',
globals: {
lwc: 'LWC',
'test-utils': 'TestUtils',
},
name: 'config',
});
const { code } = output[0];
return { code, watchFiles };
}
async function existsUp(dir, file) {
while (true) {
if (await exists(path.join(dir, file))) return true;
dir = path.join(dir, '..');
const basename = path.basename(dir);
// We should always hit __tests__, but check for system root as an escape hatch
if (basename === '__tests__' || basename === '') return false;
}
}
function createHCONFIG2JSPreprocessor(config, logger, emitter) {
const { basePath } = config;
const log = logger.create('preprocessor-lwc');
const watcher = new Watcher(config, emitter, log);
return async (_content, file, done) => {
const filePath = file.path;
const suiteDir = path.dirname(filePath);
// Wrap all the tests into a describe block with the file stricture name
const describeTitle = path.relative(basePath, suiteDir).split(path.sep).join(' ');
const { code: testCode, watchFiles: testWatchFiles } = await getTestModuleCode(filePath);
// Create a temporary module to evaluate the bundled code and extract config properties for test configuration
const configModule = new vm.Script(testCode);
const configContext = { config: {} };
vm.createContext(configContext);
configModule.runInContext(configContext);
const { expectedSSRConsoleCalls, requiredFeatureFlags } = configContext.config;
if (requiredFeatureFlags) {
requiredFeatureFlags.forEach((featureFlag) => {
lwcSsr.setFeatureFlagForTest(featureFlag, true);
});
}
try {
// You can add an `.only` file alongside an `index.spec.js` file to make it `fdescribe()`
const onlyFileExists = await existsUp(suiteDir, '.only');
const describe = onlyFileExists ? 'fdescribe' : 'describe';
const { code: componentDefCSR, watchFiles: componentWatchFilesCSR } =
await getCompiledModule(suiteDir, false);
let ssrOutput;
if (ENGINE_SERVER) {
// engine-server uses the same def as the client
watcher.watchSuite(filePath, testWatchFiles.concat(componentWatchFilesCSR));
ssrOutput = await getSsrCode(
componentDefCSR,
testCode,
path.join(suiteDir, 'ssr.js'),
expectedSSRConsoleCalls
);
} else {
// ssr-compiler has it's own def
const { code: componentDefSSR, watchFiles: componentWatchFilesSSR } =
await getCompiledModule(suiteDir, true);
watcher.watchSuite(
filePath,
testWatchFiles.concat(componentWatchFilesCSR).concat(componentWatchFilesSSR)
);
ssrOutput = await getSsrCode(
componentDefSSR.replace(`process.env.NODE_ENV === 'test-karma-lwc'`, 'true'),
testCode,
path.join(suiteDir, 'ssr.js'),
expectedSSRConsoleCalls
);
}
const newContent = format(
TEMPLATE,
JSON.stringify(ssrOutput),
componentDefCSR,
testCode,
describe,
JSON.stringify(describeTitle)
);
done(null, newContent);
} catch (error) {
const location = path.relative(basePath, filePath);
log.error('Error processing “%s”\n\n%s\n', location, error.stack || error.message);
done(error, null);
} finally {
if (requiredFeatureFlags) {
requiredFeatureFlags.forEach((featureFlag) => {
lwcSsr.setFeatureFlagForTest(featureFlag, false);
});
}
}
};
}
createHCONFIG2JSPreprocessor.$inject = ['config', 'logger', 'emitter'];
module.exports = {
'preprocessor:hydration-tests': ['factory', createHCONFIG2JSPreprocessor],
};