|
| 1 | +import path from 'node:path'; |
| 2 | +import vm from 'node:vm'; |
| 3 | +import fs from 'node:fs/promises'; |
| 4 | +import { rollup } from 'rollup'; |
| 5 | +import lwcRollupPlugin from '@lwc/rollup-plugin'; |
| 6 | +import { DISABLE_STATIC_CONTENT_OPTIMIZATION, ENGINE_SERVER } from './options.mjs'; |
| 7 | +const lwcSsr = await (ENGINE_SERVER ? import('@lwc/engine-server') : import('@lwc/ssr-runtime')); |
| 8 | + |
| 9 | +const ROOT_DIR = path.join(import.meta.dirname, '..'); |
| 10 | + |
| 11 | +const context = { |
| 12 | + LWC: lwcSsr, |
| 13 | + moduleOutput: null, |
| 14 | +}; |
| 15 | + |
| 16 | +lwcSsr.setHooks({ |
| 17 | + sanitizeHtmlContent(content) { |
| 18 | + return content; |
| 19 | + }, |
| 20 | +}); |
| 21 | + |
| 22 | +let guid = 0; |
| 23 | +const COMPONENT_UNDER_TEST = 'main'; |
| 24 | + |
| 25 | +// Like `fs.existsSync` but async |
| 26 | +async function exists(path) { |
| 27 | + try { |
| 28 | + await fs.access(path); |
| 29 | + return true; |
| 30 | + } catch (_err) { |
| 31 | + return false; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +async function getCompiledModule(dir, compileForSSR) { |
| 36 | + const bundle = await rollup({ |
| 37 | + input: path.join(dir, 'x', COMPONENT_UNDER_TEST, `${COMPONENT_UNDER_TEST}.js`), |
| 38 | + plugins: [ |
| 39 | + lwcRollupPlugin({ |
| 40 | + targetSSR: !!compileForSSR, |
| 41 | + modules: [{ dir: path.join(ROOT_DIR, dir) }], |
| 42 | + experimentalDynamicComponent: { |
| 43 | + loader: 'test-utils', |
| 44 | + strict: true, |
| 45 | + }, |
| 46 | + enableDynamicComponents: true, |
| 47 | + enableLwcOn: true, |
| 48 | + enableStaticContentOptimization: !DISABLE_STATIC_CONTENT_OPTIMIZATION, |
| 49 | + experimentalDynamicDirective: true, |
| 50 | + }), |
| 51 | + ], |
| 52 | + |
| 53 | + external: ['lwc', '@lwc/ssr-runtime', 'test-utils', '@test/loader'], // @todo: add ssr modules for test-utils and @test/loader |
| 54 | + |
| 55 | + onwarn(warning, warn) { |
| 56 | + // Ignore warnings from our own Rollup plugin |
| 57 | + if (warning.plugin !== 'rollup-plugin-lwc-compiler') { |
| 58 | + warn(warning); |
| 59 | + } |
| 60 | + }, |
| 61 | + }); |
| 62 | + |
| 63 | + const { output } = await bundle.generate({ |
| 64 | + format: 'iife', |
| 65 | + name: 'Main', |
| 66 | + globals: { |
| 67 | + lwc: 'LWC', |
| 68 | + '@lwc/ssr-runtime': 'LWC', |
| 69 | + 'test-utils': 'TestUtils', |
| 70 | + }, |
| 71 | + }); |
| 72 | + |
| 73 | + return output[0].code; |
| 74 | +} |
| 75 | + |
| 76 | +function throwOnUnexpectedConsoleCalls(runnable, expectedConsoleCalls = {}) { |
| 77 | + // The console is shared between the VM and the main realm. Here we ensure that known warnings |
| 78 | + // are ignored and any others cause an explicit error. |
| 79 | + const methods = ['error', 'warn', 'log', 'info']; |
| 80 | + const originals = {}; |
| 81 | + for (const method of methods) { |
| 82 | + // eslint-disable-next-line no-console |
| 83 | + originals[method] = console[method]; |
| 84 | + // eslint-disable-next-line no-console |
| 85 | + console[method] = function (error) { |
| 86 | + if ( |
| 87 | + method === 'warn' && |
| 88 | + // This eslint warning is a false positive due to RegExp.prototype.test |
| 89 | + // eslint-disable-next-line vitest/no-conditional-tests |
| 90 | + /Cannot set property "(inner|outer)HTML"/.test(error?.message) |
| 91 | + ) { |
| 92 | + return; |
| 93 | + } else if ( |
| 94 | + expectedConsoleCalls[method]?.some((matcher) => error.message.includes(matcher)) |
| 95 | + ) { |
| 96 | + return; |
| 97 | + } |
| 98 | + |
| 99 | + throw new Error(`Unexpected console.${method} call: ${error}`); |
| 100 | + }; |
| 101 | + } |
| 102 | + try { |
| 103 | + runnable(); |
| 104 | + } finally { |
| 105 | + Object.assign(console, originals); |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +/** |
| 110 | + * This is the function that takes SSR bundle code and test config, constructs a script that will |
| 111 | + * run in a separate JS runtime environment with its own global scope. The `context` object |
| 112 | + * (defined at the top of this file) is passed in as the global scope for that script. The script |
| 113 | + * runs, utilizing the `LWC` object that we've attached to the global scope, it sets a |
| 114 | + * new value (the rendered markup) to `globalThis.moduleOutput`, which corresponds to |
| 115 | + * `context.moduleOutput in this file's scope. |
| 116 | + * |
| 117 | + * So, script runs, generates markup, & we get that markup out and return it for use |
| 118 | + * in client-side tests. |
| 119 | + */ |
| 120 | +async function getSsrCode(moduleCode, testConfig, filename, expectedSSRConsoleCalls) { |
| 121 | + const script = new vm.Script( |
| 122 | + // FIXME: Can these IIFEs be converted to ESM imports? |
| 123 | + // No, vm.Script doesn't support that. But might be doable with experimental vm.Module |
| 124 | + ` |
| 125 | + ${testConfig}; |
| 126 | + config = config || {}; |
| 127 | + ${moduleCode}; |
| 128 | + moduleOutput = LWC.renderComponent( |
| 129 | + 'x-${COMPONENT_UNDER_TEST}-${guid++}', |
| 130 | + Main, |
| 131 | + config.props || {}, |
| 132 | + false, |
| 133 | + 'sync' |
| 134 | + ); |
| 135 | + `, |
| 136 | + { filename } |
| 137 | + ); |
| 138 | + |
| 139 | + throwOnUnexpectedConsoleCalls(() => { |
| 140 | + vm.createContext(context); |
| 141 | + script.runInContext(context); |
| 142 | + }, expectedSSRConsoleCalls); |
| 143 | + |
| 144 | + return await context.moduleOutput; |
| 145 | +} |
| 146 | + |
| 147 | +async function getTestConfig(input) { |
| 148 | + const bundle = await rollup({ |
| 149 | + input, |
| 150 | + external: ['lwc', 'test-utils', '@test/loader'], |
| 151 | + }); |
| 152 | + |
| 153 | + const { output } = await bundle.generate({ |
| 154 | + format: 'iife', |
| 155 | + globals: { |
| 156 | + lwc: 'LWC', |
| 157 | + 'test-utils': 'TestUtils', |
| 158 | + }, |
| 159 | + name: 'config', |
| 160 | + }); |
| 161 | + |
| 162 | + const { code } = output[0]; |
| 163 | + |
| 164 | + return code; |
| 165 | +} |
| 166 | + |
| 167 | +async function existsUp(dir, file) { |
| 168 | + while (true) { |
| 169 | + if (await exists(path.join(dir, file))) return true; |
| 170 | + dir = path.join(dir, '..'); |
| 171 | + const basename = path.basename(dir); |
| 172 | + if (basename === '.') return false; |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +/** |
| 177 | + * Hydration test `index.spec.js` files are actually config files, not spec files. |
| 178 | + * This function wraps those configs in the test code to be executed. |
| 179 | + */ |
| 180 | +export default async function wrapHydrationTest(filePath /* .../index.spec.js */) { |
| 181 | + const suiteDir = path.dirname(filePath); |
| 182 | + |
| 183 | + // Wrap all the tests into a describe block with the file stricture name |
| 184 | + const describeTitle = path.relative(ROOT_DIR, suiteDir).split(path.sep).join(' '); |
| 185 | + |
| 186 | + const testCode = await getTestConfig(filePath); |
| 187 | + |
| 188 | + // Create a temporary module to evaluate the bundled code and extract config properties for test configuration |
| 189 | + const configModule = new vm.Script(testCode); |
| 190 | + const configContext = { config: {} }; |
| 191 | + vm.createContext(configContext); |
| 192 | + configModule.runInContext(configContext); |
| 193 | + const { expectedSSRConsoleCalls, requiredFeatureFlags } = configContext.config; |
| 194 | + |
| 195 | + requiredFeatureFlags?.forEach((featureFlag) => { |
| 196 | + lwcSsr.setFeatureFlagForTest(featureFlag, true); |
| 197 | + }); |
| 198 | + |
| 199 | + try { |
| 200 | + // You can add an `.only` file alongside an `index.spec.js` file to make it `fdescribe()` |
| 201 | + const onlyFileExists = await existsUp(suiteDir, '.only'); |
| 202 | + |
| 203 | + const describeFn = onlyFileExists ? 'describe.only' : 'describe'; |
| 204 | + const componentDefCSR = await getCompiledModule(suiteDir, false); |
| 205 | + const componentDefSSR = ENGINE_SERVER |
| 206 | + ? componentDefCSR |
| 207 | + : await getCompiledModule(suiteDir, true); |
| 208 | + const ssrOutput = await getSsrCode( |
| 209 | + componentDefSSR, |
| 210 | + testCode, |
| 211 | + path.join(suiteDir, 'ssr.js'), |
| 212 | + expectedSSRConsoleCalls |
| 213 | + ); |
| 214 | + |
| 215 | + // FIXME: can we turn these IIFEs into ESM imports? |
| 216 | + return ` |
| 217 | + import { runTest } from '/helpers/test-hydrate.js'; |
| 218 | + import config from '/${filePath}?original=1'; |
| 219 | + ${describeFn}("${describeTitle}", () => { |
| 220 | + it('test', async () => { |
| 221 | + const ssrRendered = ${JSON.stringify(ssrOutput) /* escape quotes */}; |
| 222 | + // Component code, IIFE set as Main |
| 223 | + ${componentDefCSR}; |
| 224 | + return await runTest(ssrRendered, Main, config); |
| 225 | + }) |
| 226 | + });`; |
| 227 | + } finally { |
| 228 | + requiredFeatureFlags?.forEach((featureFlag) => { |
| 229 | + lwcSsr.setFeatureFlagForTest(featureFlag, false); |
| 230 | + }); |
| 231 | + } |
| 232 | +} |
0 commit comments