-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathtest-hydration.js
More file actions
77 lines (63 loc) · 2.43 KB
/
test-hydration.js
File metadata and controls
77 lines (63 loc) · 2.43 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
import * as LWC from 'lwc';
import { spyConsole } from '../../helpers/console';
import { setHooks } from '../../helpers/hooks';
setHooks({ sanitizeHtmlContent: (content) => content });
function parseStringToDom(html) {
return Document.parseHTMLUnsafe(html).body.firstChild;
}
function appendTestTarget(ssrText) {
const div = document.createElement('div');
const testTarget = parseStringToDom(ssrText);
div.appendChild(testTarget);
document.body.appendChild(div);
return div;
}
function setFeatureFlags(requiredFeatureFlags, value) {
requiredFeatureFlags?.forEach((featureFlag) => {
LWC.setFeatureFlagForTest(featureFlag, value);
});
}
// Must be sync to properly register tests; async behavior can happen in before/after blocks
export function runTest(configPath, componentPath, ssrRendered, focused) {
const test = focused ? it.only : it;
const description = new URL(configPath, location.href).pathname;
let consoleSpy;
let testConfig;
let Component;
beforeAll(async () => {
testConfig = await import(configPath);
Component = await import(componentPath);
setFeatureFlags(testConfig.requiredFeatureFlags, true);
});
beforeEach(async () => {
consoleSpy = spyConsole();
});
afterEach(() => {
consoleSpy.reset();
});
afterAll(() => {
setFeatureFlags(testConfig.requiredFeatureFlags, false);
});
test(description, async () => {
const container = appendTestTarget(ssrRendered);
const selector = container.firstChild.tagName.toLowerCase();
let target = container.querySelector(selector);
if (testConfig.test) {
const snapshot = testConfig.snapshot ? testConfig.snapshot(target) : {};
const props = testConfig.props || {};
const clientProps = testConfig.clientProps || props;
LWC.hydrateComponent(target, Component, clientProps);
// let's select again the target, it should be the same elements as in the snapshot
target = container.querySelector(selector);
await testConfig.test(target, snapshot, consoleSpy.calls);
} else if (testConfig.advancedTest) {
await testConfig.advancedTest(target, {
Component,
hydrateComponent: LWC.hydrateComponent.bind(LWC),
consoleSpy,
container,
selector,
});
}
});
}