forked from BuilderIO/builder
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
274 lines (240 loc) · 8.35 KB
/
index.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
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
import type {
BrowserContext,
Locator,
Page,
PlaywrightTestArgs,
PlaywrightWorkerArgs,
TestInfo,
} from '@playwright/test';
import { test as base, expect } from '@playwright/test';
import type { ServerName, Sdk } from './sdk.js';
import { fileURLToPath } from 'url';
import path from 'path';
type TestOptions = {
packageName: ServerName;
sdk: Sdk;
basePort: number;
ignoreHydrationErrors: boolean;
};
// https://github.com/microsoft/playwright/issues/14854#issuecomment-1155667859
async function screenshotOnFailure(
{ page }: PlaywrightTestArgs & PlaywrightWorkerArgs,
testInfo: TestInfo
) {
if (testInfo.status !== testInfo.expectedStatus && !process.env.CI) {
// Get a unique place for the screenshot.
const screenshotPath = testInfo.outputPath(`failure.png`);
// Add it to the report.
testInfo.attachments.push({
name: 'screenshot',
path: screenshotPath,
contentType: 'image/png',
});
// Take the screenshot itself.
await page.screenshot({ path: screenshotPath, timeout: 5000 });
}
}
const isIgnorableError = (error: Error) => {
return error.message.includes(
/**
* This error started appearing recently across all frameworks.
* It is most likely some playwright browser issue and not something we can fix in our code.
*/
"Failed to execute 'observe' on 'PressureObserver': Access to the feature \"compute pressure\" is disallowed by permissions policy"
);
};
const test = base.extend<TestOptions>({
// this is provided by `playwright.config.ts`
packageName: ['DEFAULT' as any, { option: true }],
sdk: ['DEFAULT' as any, { option: true }],
basePort: [0, { option: true }],
ignoreHydrationErrors: [false, { option: true }],
page: async ({ context, page, packageName, sdk, ignoreHydrationErrors }, use) => {
if (packageName === ('DEFAULT' as any)) {
throw new Error('`packageName` is required but was not provided.');
}
if (sdk === ('DEFAULT' as any)) {
throw new Error('`sdk` is required but was not provided.');
}
context.on('weberror', err => {
if (isIgnorableError(err.error())) return;
console.error(err.error());
throw new Error('Test failed due to error thrown in browser: ' + err.error());
});
page.on('pageerror', err => {
if (isIgnorableError(err)) return;
console.error(err);
throw new Error('Test failed due to error thrown in browser: ' + err);
});
/**
* temporarily disable hydration error checks for hydrogen until we fix them.
*/
const shouldCheckForHydrationError = packageName !== 'hydrogen' && !ignoreHydrationErrors;
if (shouldCheckForHydrationError) {
context.on('console', msg => {
const originalText = msg.text();
if (checkIfIsHydrationErrorMessage(originalText)) {
throw new Error('Hydration error detected: ' + originalText);
}
});
page.on('console', msg => {
const originalText = msg.text();
if (checkIfIsHydrationErrorMessage(originalText)) {
throw new Error('Hydration error detected: ' + originalText);
}
});
}
if (sdk === 'angular') {
page.on('console', msg => {
const originalText = msg.text();
if (originalText.includes('NG0303')) {
throw new Error('Angular input not annotated error detected: ' + originalText);
}
});
} else if (sdk === 'vue') {
page.on('console', msg => {
const originalText = msg.text();
if (originalText.toLowerCase().includes('[vue warn]:')) {
throw new Error('Vue warning detected: ' + originalText);
}
});
context.on('console', msg => {
const originalText = msg.text();
if (originalText.toLowerCase().includes('[vue warn]:')) {
throw new Error('Vue warning detected: ' + originalText);
}
});
}
await use(page);
},
});
test.afterEach(screenshotOnFailure);
export { test };
export const isSSRFramework = (packageName: ServerName | 'DEFAULT') => {
// Easier to list non-ssr than other way around.
const isNonSSR =
packageName === 'solid' ||
packageName === 'react' ||
packageName === 'svelte' ||
packageName === 'react-native-74' ||
packageName === 'react-native-76-fabric' ||
packageName === 'angular-16' ||
packageName === 'gen1-react';
return !isNonSSR;
};
export const findTextInPage = async ({ page, text }: { page: Page; text: string }) => {
await expect(page.locator(`text=${text}`)).toBeVisible();
};
export const verifyTabContent = async (
page: Page,
tabButtonText: string,
expectedVisibleContent: string,
expectedHiddenContent: string
): Promise<void> => {
await page.click(`button:has-text("${tabButtonText}")`);
const visibleContent = page.locator(`[builder-path="${expectedVisibleContent}"]`);
await expect(visibleContent).toBeVisible();
const hiddenContent = page.locator(`[builder-path="${expectedHiddenContent}"]`);
await expect(hiddenContent).not.toBeVisible();
};
export const checkIsRN = (sdk: Sdk) => sdk === 'reactNative';
export const checkIsGen1React = (sdk: Sdk) => sdk === 'oldReact';
type SDK_EXCLUSION_DICT = {
[X in Sdk]?: boolean;
};
/**
* Useful tool to skip tests when features aren't implemented in a specific output yet.
* We use the negative tense, so that the default behavior is to run the test, unless specifically omitted.
*
*/
export const excludeTestFor = (sdks: SDK_EXCLUSION_DICT | Array<Sdk>, sdk: Sdk) => {
const sdkIsExcluded = Array.isArray(sdks) ? sdks.includes(sdk) : sdks[sdk];
return sdkIsExcluded || false;
};
/**
* We exclude some new tests from old React until we fix them.
*/
export const excludeGen1 = (sdk: Sdk) => excludeTestFor({ oldReact: true }, sdk);
/**
* We exclude some tests from SDKs which are not from old React.
*/
export const excludeGen2 = (sdk: Sdk) =>
excludeTestFor(
{
qwik: true,
react: true,
reactNative: true,
rsc: true,
solid: true,
svelte: true,
vue: true,
angular: true,
},
sdk
);
export const excludeRn = (sdk: Sdk) => excludeTestFor({ reactNative: true }, sdk);
export const getElementStyleValue = async ({
locator,
cssProperty,
}: {
locator: Locator;
cssProperty: string;
}) => {
return locator.evaluate((e, cssProperty) => {
return getComputedStyle(e).getPropertyValue(cssProperty);
}, cssProperty);
};
export type ExpectedStyles = Record<string, string>;
export const expectStylesForElement = async ({
expected,
locator,
}: {
locator: Locator;
expected: ExpectedStyles;
}) => {
for (const property of Object.keys(expected)) {
await expect(locator).toHaveCSS(property, expected[property]);
}
};
export const getBuilderSessionIdCookie = async ({ context }: { context: BrowserContext }) => {
const cookies = await context.cookies();
const builderSessionCookie = cookies.find(cookie => cookie.name === 'builderSessionId');
return builderSessionCookie;
};
export async function testClickAndVerifyVisibility(
page: Page,
buttonText: string,
contentText: string
) {
await page.click(`button:has-text("${buttonText}")`);
const content = await page.waitForSelector(`div:has-text("${contentText}")`, {
state: 'visible',
});
return content.isVisible();
}
export const checkIfIsHydrationErrorMessage = (_text: string) => {
const text = _text.toLowerCase();
const isVueHydrationMismatch =
text.includes('[vue warn]') && (text.includes('hydration') || text.includes('mismatch'));
const isReactHydrationMismatch =
text.includes('did not expect server') ||
text.includes('content does not match') ||
text.includes('did not match') ||
text.includes('hydration') ||
text.includes('mismatch') ||
text.includes('minified react error #');
const filterHydrationmismatchMessages = isVueHydrationMismatch || isReactHydrationMismatch;
return filterHydrationmismatchMessages;
};
export const getClassSelector = (className: string, sdk: Sdk) => {
return checkIsRN(sdk) ? `[data-class*=${className}]` : `.${className}`;
};
const currentFilename = fileURLToPath(import.meta.url);
const currentDirname = path.dirname(currentFilename);
export const mockFolderPath = path.join(currentDirname, '..', 'mocks');
export const mapSdkName = (sdk: string): string => {
return sdk === 'oldReact' ? 'react' : sdk;
};
export const getSdkGeneration = (sdk: string): string => {
return sdk === 'oldReact' ? '1' : '2';
};