-
Notifications
You must be signed in to change notification settings - Fork 401
/
Copy pathfixtures.spec.ts
executable file
·214 lines (184 loc) · 6.96 KB
/
fixtures.spec.ts
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
/*
* Copyright (c) 2020, 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
*/
import fs from 'fs';
import path from 'path';
import { rollup, RollupLog } from 'rollup';
import lwcRollupPlugin from '@lwc/rollup-plugin';
import { isVoidElement, HTML_NAMESPACE } from '@lwc/shared';
import { testFixtureDir } from '@lwc/jest-utils-lwc-internals';
import type * as lwc from '../index';
interface FixtureModule {
tagName: string;
default: typeof lwc.LightningElement;
props?: { [key: string]: any };
features?: any[];
}
jest.setTimeout(10_000 /* 10 seconds */);
async function compileFixture({ input, dirname }: { input: string; dirname: string }) {
const modulesDir = path.resolve(dirname, './modules');
const outputFile = path.resolve(dirname, './dist/compiled.js');
// TODO [#3331]: this is only needed to silence warnings on lwc:dynamic, remove in 246.
const warnings: RollupLog[] = [];
const bundle = await rollup({
input,
external: ['lwc'],
plugins: [
lwcRollupPlugin({
enableDynamicComponents: true,
modules: [
{
dir: modulesDir,
},
],
}),
],
onwarn(warning, warn) {
if (warning.message.includes('LWC1187')) {
// TODO [#3331]: The existing lwc:dynamic fixture test will generate warnings that can be safely suppressed.
// The warning message is expected and appears when the compiler detects usage of the directive.
// We plan to remove the directive in a future release, see #3331 for details.
warnings.push(warning);
} else {
warn(warning);
}
},
});
await bundle.write({
file: outputFile,
format: 'cjs',
exports: 'named',
});
return outputFile;
}
/**
* Naive HTML fragment formatter.
*
* This is a replacement for Prettier HTML formatting. Prettier formatting is too aggressive for
* fixture testing. It not only indent the HTML code but also fixes HTML issues. For testing we want
* to make sure that the fixture file is as close as possible to what the engine produces.
* @param src the original HTML fragment.
* @returns the formatter HTML fragment.
*/
function formatHTML(src: string): string {
let res = '';
let pos = 0;
let start = pos;
let depth = 0;
const getPadding = () => {
return ' '.repeat(depth);
};
while (pos < src.length) {
// Consume element tags and comments.
if (src.charAt(pos) === '<') {
const tagNameMatch = src.slice(pos).match(/(\w+)/);
// Special handling for `<style>` tags – these are not encoded, so we may hit '<' or '>'
// inside the text content. So we just serialize it as-is.
if (tagNameMatch![0] === 'style') {
const styleMatch = src.slice(pos).match(/<style([\s\S]*?)>([\s\S]*?)<\/style>/);
if (styleMatch) {
// opening tag
const [wholeMatch, attrs, textContent] = styleMatch;
res += getPadding() + `<style${attrs}>` + '\n';
depth++;
res += getPadding() + textContent + '\n';
depth--;
res += getPadding() + '</style>' + '\n';
start = pos = pos + wholeMatch.length;
continue;
}
}
const isVoid = isVoidElement(tagNameMatch![0], HTML_NAMESPACE);
const isClosing = src.charAt(pos + 1) === '/';
const isComment =
src.charAt(pos + 1) === '!' &&
src.charAt(pos + 2) === '-' &&
src.charAt(pos + 3) === '-';
start = pos;
while (src.charAt(pos++) !== '>') {
// Keep advancing until consuming the closing tag.
}
// Adjust current depth and print the element tag or comment.
if (isClosing) {
depth--;
}
res += getPadding() + src.slice(start, pos) + '\n';
const isSelfClosing = src.charAt(pos - 2) === '/';
if (!isClosing && !isSelfClosing && !isVoid && !isComment) {
depth++;
}
}
// Consume text content.
start = pos;
while (src.charAt(pos) !== '<' && pos < src.length) {
pos++;
}
if (start !== pos) {
res += getPadding() + src.slice(start, pos) + '\n';
}
}
return res.trim();
}
function testFixtures() {
testFixtureDir(
{
root: path.resolve(__dirname, 'fixtures'),
pattern: '**/index.js',
},
async ({ filename, dirname }) => {
const configPath = path.resolve(dirname, 'config.json');
let config: any = {};
if (fs.existsSync(configPath)) {
config = require(configPath);
}
const compiledFixturePath = await compileFixture({
input: filename,
dirname,
});
// The LWC engine holds global state like the current VM index, which has an impact on
// the generated HTML IDs. So the engine has to be re-evaluated between tests.
// On top of this, the engine also checks if the component constructor is an instance of
// the LightningElement. Therefor the compiled module should also be evaluated in the
// same sandbox registry as the engine.
let lwcEngineServer: typeof lwc | undefined;
let module: FixtureModule | undefined;
jest.isolateModules(() => {
lwcEngineServer = require('../index');
module = require(compiledFixturePath);
});
const features = module!.features ?? [];
features.forEach((flag) => {
lwcEngineServer!.setFeatureFlagForTest(flag, true);
});
lwcEngineServer!.setHooks({
sanitizeHtmlContent(content: unknown) {
return content as string;
},
});
let result;
let err;
try {
result = lwcEngineServer!.renderComponent(
module!.tagName,
module!.default,
config.props || {}
);
} catch (_err: any) {
err = _err.message;
}
features.forEach((flag) => {
lwcEngineServer!.setFeatureFlagForTest(flag, false);
});
return {
'expected.html': result ? formatHTML(result) : undefined,
'error.txt': err,
};
}
);
}
describe('fixtures', () => {
testFixtures();
});