cherry-pick(#28975): chore: refactor import processing in ct

This commit is contained in:
Pavel Feldman 2024-01-12 20:02:27 -08:00 committed by Pavel
parent 4d9f923dfe
commit d47ed6a076
19 changed files with 435 additions and 620 deletions

View file

@ -0,0 +1,2 @@
[importRegistry.ts]
../types/**

View file

@ -0,0 +1,59 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { ImportRef } from '../types/component';
export class ImportRegistry {
private _registry = new Map<string, () => Promise<any>>();
initialize(components: Record<string, () => Promise<any>>) {
for (const [name, value] of Object.entries(components))
this._registry.set(name, value);
}
async resolveImports(value: any): Promise<any> {
if (value === null || typeof value !== 'object')
return value;
if (this._isImportRef(value)) {
const importFunction = this._registry.get(value.id);
if (!importFunction)
throw new Error(`Unregistered component: ${value.id}. Following components are registered: ${[...this._registry.keys()]}`);
let importedObject = await importFunction();
if (!importedObject)
throw new Error(`Could not resolve component: ${value.id}.`);
if (value.property) {
importedObject = importedObject[value.property];
if (!importedObject)
throw new Error(`Could not instantiate component: ${value.id}.${value.property}.`);
}
return importedObject;
}
if (Array.isArray(value)) {
const result = [];
for (const item of value)
result.push(await this.resolveImports(item));
return result;
}
const result: any = {};
for (const [key, prop] of Object.entries(value))
result[key] = await this.resolveImports(prop);
return result;
}
private _isImportRef(value: any): value is ImportRef {
return typeof value === 'object' && value && value.__pw_type === 'importRef';
}
}

View file

@ -15,7 +15,7 @@
*/ */
import type { Fixtures, Locator, Page, BrowserContextOptions, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, BrowserContext } from 'playwright/test'; import type { Fixtures, Locator, Page, BrowserContextOptions, PlaywrightTestArgs, PlaywrightTestOptions, PlaywrightWorkerArgs, PlaywrightWorkerOptions, BrowserContext } from 'playwright/test';
import type { Component, JsxComponent, MountOptions } from '../types/component'; import type { Component, ImportRef, JsxComponent, MountOptions, ObjectComponentOptions } from '../types/component';
import type { ContextReuseMode, FullConfigInternal } from '../../playwright/src/common/config'; import type { ContextReuseMode, FullConfigInternal } from '../../playwright/src/common/config';
let boundCallbacksForMount: Function[] = []; let boundCallbacksForMount: Function[] = [];
@ -25,61 +25,65 @@ interface MountResult extends Locator {
update(options: Omit<MountOptions, 'hooksConfig'> | string | JsxComponent): Promise<void>; update(options: Omit<MountOptions, 'hooksConfig'> | string | JsxComponent): Promise<void>;
} }
export const fixtures: Fixtures< type TestFixtures = PlaywrightTestArgs & PlaywrightTestOptions & {
PlaywrightTestArgs & PlaywrightTestOptions & { mount: (component: any, options: any) => Promise<MountResult>;
mount: (component: any, options: any) => Promise<MountResult>; };
}, type WorkerFixtures = PlaywrightWorkerArgs & PlaywrightWorkerOptions & { _ctWorker: { context: BrowserContext | undefined, hash: string } };
PlaywrightWorkerArgs & PlaywrightWorkerOptions & { _ctWorker: { context: BrowserContext | undefined, hash: string } }, type BaseTestFixtures = {
{ _contextFactory: (options?: BrowserContextOptions) => Promise<BrowserContext>, _contextReuseMode: ContextReuseMode }> = { _contextFactory: (options?: BrowserContextOptions) => Promise<BrowserContext>,
_contextReuseMode: ContextReuseMode
};
_contextReuseMode: 'when-possible', export const fixtures: Fixtures<TestFixtures, WorkerFixtures, BaseTestFixtures> = {
serviceWorkers: 'block', _contextReuseMode: 'when-possible',
_ctWorker: [{ context: undefined, hash: '' }, { scope: 'worker' }], serviceWorkers: 'block',
page: async ({ page }, use, info) => { _ctWorker: [{ context: undefined, hash: '' }, { scope: 'worker' }],
if (!((info as any)._configInternal as FullConfigInternal).defineConfigWasUsed)
throw new Error('Component testing requires the use of the defineConfig() in your playwright-ct.config.{ts,js}: https://aka.ms/playwright/ct-define-config');
await (page as any)._wrapApiCall(async () => {
await page.exposeFunction('__ct_dispatch', (ordinal: number, args: any[]) => {
boundCallbacksForMount[ordinal](...args);
});
await page.goto(process.env.PLAYWRIGHT_TEST_BASE_URL!);
}, true);
await use(page);
},
mount: async ({ page }, use) => { page: async ({ page }, use, info) => {
await use(async (component: JsxComponent | string, options?: MountOptions) => { if (!((info as any)._configInternal as FullConfigInternal).defineConfigWasUsed)
const selector = await (page as any)._wrapApiCall(async () => { throw new Error('Component testing requires the use of the defineConfig() in your playwright-ct.config.{ts,js}: https://aka.ms/playwright/ct-define-config');
return await innerMount(page, component, options); await (page as any)._wrapApiCall(async () => {
}, true); await page.exposeFunction('__ct_dispatch', (ordinal: number, args: any[]) => {
const locator = page.locator(selector); boundCallbacksForMount[ordinal](...args);
return Object.assign(locator, {
unmount: async () => {
await locator.evaluate(async () => {
const rootElement = document.getElementById('root')!;
await window.playwrightUnmount(rootElement);
});
},
update: async (options: JsxComponent | Omit<MountOptions, 'hooksConfig'>) => {
if (isJsxApi(options))
return await innerUpdate(page, options);
await innerUpdate(page, component, options);
}
});
}); });
boundCallbacksForMount = []; await page.goto(process.env.PLAYWRIGHT_TEST_BASE_URL!);
}, }, true);
}; await use(page);
},
function isJsxApi(options: Record<string, unknown>): options is JsxComponent { mount: async ({ page }, use) => {
return options?.kind === 'jsx'; await use(async (componentRef: JsxComponent | ImportRef, options?: ObjectComponentOptions & MountOptions) => {
const selector = await (page as any)._wrapApiCall(async () => {
return await innerMount(page, componentRef, options);
}, true);
const locator = page.locator(selector);
return Object.assign(locator, {
unmount: async () => {
await locator.evaluate(async () => {
const rootElement = document.getElementById('root')!;
await window.playwrightUnmount(rootElement);
});
},
update: async (options: JsxComponent | ObjectComponentOptions) => {
if (isJsxComponent(options))
return await innerUpdate(page, options);
await innerUpdate(page, componentRef, options);
}
});
});
boundCallbacksForMount = [];
},
};
function isJsxComponent(component: any): component is JsxComponent {
return typeof component === 'object' && component && component.__pw_type === 'jsx';
} }
async function innerUpdate(page: Page, jsxOrType: JsxComponent | string, options: Omit<MountOptions, 'hooksConfig'> = {}): Promise<void> { async function innerUpdate(page: Page, componentRef: JsxComponent | ImportRef, options: ObjectComponentOptions = {}): Promise<void> {
const component = createComponent(jsxOrType, options); const component = createComponent(componentRef, options);
wrapFunctions(component, page, boundCallbacksForMount); wrapFunctions(component, page, boundCallbacksForMount);
await page.evaluate(async ({ component }) => { await page.evaluate(async ({ component }) => {
@ -97,13 +101,14 @@ async function innerUpdate(page: Page, jsxOrType: JsxComponent | string, options
}; };
unwrapFunctions(component); unwrapFunctions(component);
component = await window.__pwRegistry.resolveImports(component);
const rootElement = document.getElementById('root')!; const rootElement = document.getElementById('root')!;
return await window.playwrightUpdate(rootElement, component); return await window.playwrightUpdate(rootElement, component);
}, { component }); }, { component });
} }
async function innerMount(page: Page, jsxOrType: JsxComponent | string, options: MountOptions = {}): Promise<string> { async function innerMount(page: Page, componentRef: JsxComponent | ImportRef, options: ObjectComponentOptions & MountOptions = {}): Promise<string> {
const component = createComponent(jsxOrType, options); const component = createComponent(componentRef, options);
wrapFunctions(component, page, boundCallbacksForMount); wrapFunctions(component, page, boundCallbacksForMount);
// WebKit does not wait for deferred scripts. // WebKit does not wait for deferred scripts.
@ -130,7 +135,7 @@ async function innerMount(page: Page, jsxOrType: JsxComponent | string, options:
rootElement.id = 'root'; rootElement.id = 'root';
document.body.appendChild(rootElement); document.body.appendChild(rootElement);
} }
component = await window.__pwRegistry.resolveImports(component);
await window.playwrightMount(component, rootElement, hooksConfig); await window.playwrightMount(component, rootElement, hooksConfig);
return '#root >> internal:control=component'; return '#root >> internal:control=component';
@ -138,9 +143,14 @@ async function innerMount(page: Page, jsxOrType: JsxComponent | string, options:
return selector; return selector;
} }
function createComponent(jsxOrType: JsxComponent | string, options: Omit<MountOptions, 'hooksConfig'> = {}): Component { function createComponent(component: JsxComponent | ImportRef, options: ObjectComponentOptions = {}): Component {
if (typeof jsxOrType !== 'string') return jsxOrType; if (component.__pw_type === 'jsx')
return { __pw_component_marker: true, kind: 'object', type: jsxOrType, options }; return component;
return {
__pw_type: 'object-component',
type: component,
...options,
};
} }
function wrapFunctions(object: any, page: Page, callbacks: Function[]) { function wrapFunctions(object: any, page: Page, callbacks: Function[]) {

View file

@ -20,9 +20,8 @@ import { types, declare, traverse } from 'playwright/lib/transform/babelBundle';
import { resolveImportSpecifierExtension } from 'playwright/lib/util'; import { resolveImportSpecifierExtension } from 'playwright/lib/util';
const t: typeof T = types; const t: typeof T = types;
const fullNames = new Map<string, string | undefined>();
let componentNames: Set<string>; let componentNames: Set<string>;
let componentIdentifiers: Set<T.Identifier>; let componentImports: Map<string, ImportInfo>;
export default declare((api: BabelAPI) => { export default declare((api: BabelAPI) => {
api.assertVersion(7); api.assertVersion(7);
@ -30,11 +29,41 @@ export default declare((api: BabelAPI) => {
const result: PluginObj = { const result: PluginObj = {
name: 'playwright-debug-transform', name: 'playwright-debug-transform',
visitor: { visitor: {
Program(path) { Program: {
fullNames.clear(); enter(path) {
const result = collectComponentUsages(path.node); const result = collectComponentUsages(path.node);
componentNames = result.names; componentNames = result.names;
componentIdentifiers = result.identifiers; componentImports = new Map();
},
exit(path) {
let firstDeclaration: any;
let lastImportDeclaration: any;
path.get('body').forEach(p => {
if (p.isImportDeclaration())
lastImportDeclaration = p;
else if (!firstDeclaration)
firstDeclaration = p;
});
const insertionPath = lastImportDeclaration || firstDeclaration;
if (!insertionPath)
return;
for (const componentImport of [...componentImports.values()].reverse()) {
insertionPath.insertAfter(
t.variableDeclaration(
'const',
[
t.variableDeclarator(
t.identifier(componentImport.localName),
t.objectExpression([
t.objectProperty(t.identifier('__pw_type'), t.stringLiteral('importRef')),
t.objectProperty(t.identifier('id'), t.stringLiteral(componentImport.id)),
]),
)
]
)
);
}
}
}, },
ImportDeclaration(p) { ImportDeclaration(p) {
@ -44,14 +73,12 @@ export default declare((api: BabelAPI) => {
let components = 0; let components = 0;
for (const specifier of importNode.specifiers) { for (const specifier of importNode.specifiers) {
const specifierName = specifier.local.name;
const componentName = componentNames.has(specifierName) ? specifierName : [...componentNames].find(c => c.startsWith(specifierName + '.'));
if (!componentName)
continue;
if (t.isImportNamespaceSpecifier(specifier)) if (t.isImportNamespaceSpecifier(specifier))
continue; continue;
const { fullName } = componentInfo(specifier, importNode.source.value, this.filename!, componentName); const info = importInfo(importNode, specifier, this.filename!);
fullNames.set(componentName, fullName); if (!componentNames.has(info.localName))
continue;
componentImports.set(info.localName, info);
++components; ++components;
} }
@ -62,76 +89,20 @@ export default declare((api: BabelAPI) => {
} }
}, },
Identifier(p) { MemberExpression(path) {
if (componentIdentifiers.has(p.node)) { if (!t.isIdentifier(path.node.object))
const componentName = fullNames.get(p.node.name) || p.node.name;
p.replaceWith(t.stringLiteral(componentName));
}
},
JSXElement(path) {
const jsxElement = path.node;
const jsxName = jsxElement.openingElement.name;
let nameOrExpression: string = '';
if (t.isJSXIdentifier(jsxName))
nameOrExpression = jsxName.name;
else if (t.isJSXMemberExpression(jsxName) && t.isJSXIdentifier(jsxName.object) && t.isJSXIdentifier(jsxName.property))
nameOrExpression = jsxName.object.name + '.' + jsxName.property.name;
if (!nameOrExpression)
return; return;
const componentName = fullNames.get(nameOrExpression) || nameOrExpression; if (!componentImports.has(path.node.object.name))
return;
const props: (T.ObjectProperty | T.SpreadElement)[] = []; if (!t.isIdentifier(path.node.property))
return;
for (const jsxAttribute of jsxElement.openingElement.attributes) { path.replaceWith(
if (t.isJSXAttribute(jsxAttribute)) { t.objectExpression([
let namespace: T.JSXIdentifier | undefined; t.spreadElement(t.identifier(path.node.object.name)),
let name: T.JSXIdentifier | undefined; t.objectProperty(t.identifier('property'), t.stringLiteral(path.node.property.name)),
if (t.isJSXNamespacedName(jsxAttribute.name)) { ])
namespace = jsxAttribute.name.namespace; );
name = jsxAttribute.name.name; },
} else if (t.isJSXIdentifier(jsxAttribute.name)) {
name = jsxAttribute.name;
}
if (!name)
continue;
const attrName = (namespace ? namespace.name + ':' : '') + name.name;
if (t.isStringLiteral(jsxAttribute.value))
props.push(t.objectProperty(t.stringLiteral(attrName), jsxAttribute.value));
else if (t.isJSXExpressionContainer(jsxAttribute.value) && t.isExpression(jsxAttribute.value.expression))
props.push(t.objectProperty(t.stringLiteral(attrName), jsxAttribute.value.expression));
else if (jsxAttribute.value === null)
props.push(t.objectProperty(t.stringLiteral(attrName), t.booleanLiteral(true)));
else
props.push(t.objectProperty(t.stringLiteral(attrName), t.nullLiteral()));
} else if (t.isJSXSpreadAttribute(jsxAttribute)) {
props.push(t.spreadElement(jsxAttribute.argument));
}
}
const children: (T.Expression | T.SpreadElement)[] = [];
for (const child of jsxElement.children) {
if (t.isJSXText(child))
children.push(t.stringLiteral(child.value));
else if (t.isJSXElement(child))
children.push(child);
else if (t.isJSXExpressionContainer(child) && !t.isJSXEmptyExpression(child.expression))
children.push(child.expression);
else if (t.isJSXSpreadChild(child))
children.push(t.spreadElement(child.expression));
}
const component: T.ObjectProperty[] = [
t.objectProperty(t.identifier('__pw_component_marker'), t.booleanLiteral(true)),
t.objectProperty(t.identifier('kind'), t.stringLiteral('jsx')),
t.objectProperty(t.identifier('type'), t.stringLiteral(componentName)),
t.objectProperty(t.identifier('props'), t.objectExpression(props)),
];
if (children.length)
component.push(t.objectProperty(t.identifier('children'), t.arrayExpression(children)));
path.replaceWith(t.objectExpression(component));
}
} }
}; };
return result; return result;
@ -140,7 +111,6 @@ export default declare((api: BabelAPI) => {
export function collectComponentUsages(node: T.Node) { export function collectComponentUsages(node: T.Node) {
const importedLocalNames = new Set<string>(); const importedLocalNames = new Set<string>();
const names = new Set<string>(); const names = new Set<string>();
const identifiers = new Set<T.Identifier>();
traverse(node, { traverse(node, {
enter: p => { enter: p => {
@ -162,7 +132,7 @@ export function collectComponentUsages(node: T.Node) {
if (t.isJSXIdentifier(p.node.openingElement.name)) if (t.isJSXIdentifier(p.node.openingElement.name))
names.add(p.node.openingElement.name.name); names.add(p.node.openingElement.name.name);
if (t.isJSXMemberExpression(p.node.openingElement.name) && t.isJSXIdentifier(p.node.openingElement.name.object) && t.isJSXIdentifier(p.node.openingElement.name.property)) if (t.isJSXMemberExpression(p.node.openingElement.name) && t.isJSXIdentifier(p.node.openingElement.name.object) && t.isJSXIdentifier(p.node.openingElement.name.property))
names.add(p.node.openingElement.name.object.name + '.' + p.node.openingElement.name.property.name); names.add(p.node.openingElement.name.object.name);
} }
// Treat mount(identifier, ...) as component usage if it is in the importedLocalNames list. // Treat mount(identifier, ...) as component usage if it is in the importedLocalNames list.
@ -173,45 +143,46 @@ export function collectComponentUsages(node: T.Node) {
return; return;
names.add(arg.name); names.add(arg.name);
identifiers.add(arg);
} }
} }
}); });
return { names, identifiers }; return { names };
} }
export type ComponentInfo = { export type ImportInfo = {
fullName: string; id: string;
importPath: string;
isModuleOrAlias: boolean; isModuleOrAlias: boolean;
importedName?: string; importPath: string;
importedNameProperty?: string; localName: string;
deps: string[]; remoteName: string | undefined;
}; };
export function componentInfo(specifier: T.ImportSpecifier | T.ImportDefaultSpecifier, importSource: string, filename: string, componentName: string): ComponentInfo { export function importInfo(importNode: T.ImportDeclaration, specifier: T.ImportSpecifier | T.ImportDefaultSpecifier, filename: string): ImportInfo {
const importSource = importNode.source.value;
const isModuleOrAlias = !importSource.startsWith('.'); const isModuleOrAlias = !importSource.startsWith('.');
const unresolvedImportPath = path.resolve(path.dirname(filename), importSource); const unresolvedImportPath = path.resolve(path.dirname(filename), importSource);
// Support following notations for Button.tsx: // Support following notations for Button.tsx:
// - import { Button } from './Button.js' - via resolveImportSpecifierExtension // - import { Button } from './Button.js' - via resolveImportSpecifierExtension
// - import { Button } from './Button' - via require.resolve // - import { Button } from './Button' - via require.resolve
const importPath = isModuleOrAlias ? importSource : resolveImportSpecifierExtension(unresolvedImportPath) || require.resolve(unresolvedImportPath); const importPath = isModuleOrAlias ? importSource : resolveImportSpecifierExtension(unresolvedImportPath) || require.resolve(unresolvedImportPath);
const prefix = importPath.replace(/[^\w_\d]/g, '_'); const idPrefix = importPath.replace(/[^\w_\d]/g, '_');
const pathInfo = { importPath, isModuleOrAlias };
const specifierName = specifier.local.name; const result: ImportInfo = {
let fullNameSuffix = ''; id: idPrefix,
let importedNameProperty = ''; importPath,
if (componentName !== specifierName) { isModuleOrAlias,
const suffix = componentName.substring(specifierName.length + 1); localName: specifier.local.name,
fullNameSuffix = '_' + suffix; remoteName: undefined,
importedNameProperty = '.' + suffix; };
if (t.isImportDefaultSpecifier(specifier)) {
} else if (t.isIdentifier(specifier.imported)) {
result.remoteName = specifier.imported.name;
} else {
result.remoteName = specifier.imported.value;
} }
if (t.isImportDefaultSpecifier(specifier)) if (result.remoteName)
return { fullName: prefix + fullNameSuffix, importedNameProperty, deps: [], ...pathInfo }; result.id += '_' + result.remoteName;
return result;
if (t.isIdentifier(specifier.imported))
return { fullName: prefix + '_' + specifier.imported.name + fullNameSuffix, importedName: specifier.imported.name, importedNameProperty, deps: [], ...pathInfo };
return { fullName: prefix + '_' + specifier.imported.value + fullNameSuffix, importedName: specifier.imported.value, importedNameProperty, deps: [], ...pathInfo };
} }

View file

@ -19,7 +19,6 @@ import type { PlaywrightTestConfig as BasePlaywrightTestConfig, FullConfig } fro
import type { InlineConfig, Plugin, ResolveFn, ResolvedConfig, UserConfig } from 'vite'; import type { InlineConfig, Plugin, ResolveFn, ResolvedConfig, UserConfig } from 'vite';
import type { TestRunnerPlugin } from '../../playwright/src/plugins'; import type { TestRunnerPlugin } from '../../playwright/src/plugins';
import type { ComponentInfo } from './tsxTransform';
import type { AddressInfo } from 'net'; import type { AddressInfo } from 'net';
import type { PluginContext } from 'rollup'; import type { PluginContext } from 'rollup';
import { debug } from 'playwright-core/lib/utilsBundle'; import { debug } from 'playwright-core/lib/utilsBundle';
@ -31,14 +30,23 @@ import { stoppable } from 'playwright/lib/utilsBundle';
import { assert, calculateSha1 } from 'playwright-core/lib/utils'; import { assert, calculateSha1 } from 'playwright-core/lib/utils';
import { getPlaywrightVersion } from 'playwright-core/lib/utils'; import { getPlaywrightVersion } from 'playwright-core/lib/utils';
import { setExternalDependencies } from 'playwright/lib/transform/compilationCache'; import { setExternalDependencies } from 'playwright/lib/transform/compilationCache';
import { collectComponentUsages, componentInfo } from './tsxTransform'; import { collectComponentUsages, importInfo } from './tsxTransform';
import { version as viteVersion, build, preview, mergeConfig } from 'vite'; import { version as viteVersion, build, preview, mergeConfig } from 'vite';
import type { ImportInfo } from './tsxTransform';
const log = debug('pw:vite'); const log = debug('pw:vite');
let stoppableServer: any; let stoppableServer: any;
const playwrightVersion = getPlaywrightVersion(); const playwrightVersion = getPlaywrightVersion();
type ComponentInfo = {
id: string;
importPath: string;
isModuleOrAlias: boolean;
remoteName: string | undefined;
deps: string[];
};
type CtConfig = BasePlaywrightTestConfig['use'] & { type CtConfig = BasePlaywrightTestConfig['use'] & {
ctPort?: number; ctPort?: number;
ctTemplateDir?: string; ctTemplateDir?: string;
@ -107,7 +115,13 @@ export function createPlugin(
let buildExists = false; let buildExists = false;
let buildInfo: BuildInfo; let buildInfo: BuildInfo;
const registerSource = await fs.promises.readFile(registerSourceFile, 'utf-8'); const importRegistryFile = await fs.promises.readFile(path.resolve(__dirname, 'importRegistry.js'), 'utf-8');
assert(importRegistryFile.includes(importRegistryPrefix));
assert(importRegistryFile.includes(importRegistrySuffix));
const importRegistrySource = importRegistryFile.replace(importRegistryPrefix, '').replace(importRegistrySuffix, '') + `
window.__pwRegistry = new ImportRegistry();
`;
const registerSource = importRegistrySource + await fs.promises.readFile(registerSourceFile, 'utf-8');
const registerSourceHash = calculateSha1(registerSource); const registerSourceHash = calculateSha1(registerSource);
try { try {
@ -269,11 +283,19 @@ async function checkNewTests(suite: Suite, buildInfo: BuildInfo, componentRegist
for (const testFile of testFiles) { for (const testFile of testFiles) {
const timestamp = (await fs.promises.stat(testFile)).mtimeMs; const timestamp = (await fs.promises.stat(testFile)).mtimeMs;
if (buildInfo.tests[testFile]?.timestamp !== timestamp) { if (buildInfo.tests[testFile]?.timestamp !== timestamp) {
const components = await parseTestFile(testFile); const componentImports = await parseTestFile(testFile);
log('changed test:', testFile); log('changed test:', testFile);
for (const component of components) for (const componentImport of componentImports) {
componentRegistry.set(component.fullName, component); const ci: ComponentInfo = {
buildInfo.tests[testFile] = { timestamp, components: components.map(c => c.fullName) }; id: componentImport.id,
isModuleOrAlias: componentImport.isModuleOrAlias,
importPath: componentImport.importPath,
remoteName: componentImport.remoteName,
deps: [],
};
componentRegistry.set(componentImport.id, { ...ci, deps: [] });
}
buildInfo.tests[testFile] = { timestamp, components: componentImports.map(c => c.id) };
hasNewTests = true; hasNewTests = true;
} }
} }
@ -283,7 +305,7 @@ async function checkNewTests(suite: Suite, buildInfo: BuildInfo, componentRegist
async function checkNewComponents(buildInfo: BuildInfo, componentRegistry: ComponentRegistry): Promise<boolean> { async function checkNewComponents(buildInfo: BuildInfo, componentRegistry: ComponentRegistry): Promise<boolean> {
const newComponents = [...componentRegistry.keys()]; const newComponents = [...componentRegistry.keys()];
const oldComponents = new Map(buildInfo.components.map(c => [c.fullName, c])); const oldComponents = new Map(buildInfo.components.map(c => [c.id, c]));
let hasNewComponents = false; let hasNewComponents = false;
for (const c of newComponents) { for (const c of newComponents) {
@ -293,17 +315,17 @@ async function checkNewComponents(buildInfo: BuildInfo, componentRegistry: Compo
} }
} }
for (const c of oldComponents.values()) for (const c of oldComponents.values())
componentRegistry.set(c.fullName, c); componentRegistry.set(c.id, c);
return hasNewComponents; return hasNewComponents;
} }
async function parseTestFile(testFile: string): Promise<ComponentInfo[]> { async function parseTestFile(testFile: string): Promise<ImportInfo[]> {
const text = await fs.promises.readFile(testFile, 'utf-8'); const text = await fs.promises.readFile(testFile, 'utf-8');
const ast = parse(text, { errorRecovery: true, plugins: ['typescript', 'jsx'], sourceType: 'module' }); const ast = parse(text, { errorRecovery: true, plugins: ['typescript', 'jsx'], sourceType: 'module' });
const componentUsages = collectComponentUsages(ast); const componentUsages = collectComponentUsages(ast);
const componentNames = componentUsages.names; const componentNames = componentUsages.names;
const result: ComponentInfo[] = []; const result: ImportInfo[] = [];
traverse(ast, { traverse(ast, {
enter: p => { enter: p => {
@ -313,13 +335,12 @@ async function parseTestFile(testFile: string): Promise<ComponentInfo[]> {
return; return;
for (const specifier of importNode.specifiers) { for (const specifier of importNode.specifiers) {
const specifierName = specifier.local.name;
const componentName = componentNames.has(specifierName) ? specifierName : [...componentNames].find(c => c.startsWith(specifierName + '.'));
if (!componentName)
continue;
if (t.isImportNamespaceSpecifier(specifier)) if (t.isImportNamespaceSpecifier(specifier))
continue; continue;
result.push(componentInfo(specifier, importNode.source.value, testFile, componentName)); const info = importInfo(importNode, specifier, testFile);
if (!componentNames.has(info.localName))
continue;
result.push(info);
} }
} }
} }
@ -370,13 +391,10 @@ function vitePlugin(registerSource: string, templateDir: string, buildInfo: Buil
for (const [alias, value] of componentRegistry) { for (const [alias, value] of componentRegistry) {
const importPath = value.isModuleOrAlias ? value.importPath : './' + path.relative(folder, value.importPath).replace(/\\/g, '/'); const importPath = value.isModuleOrAlias ? value.importPath : './' + path.relative(folder, value.importPath).replace(/\\/g, '/');
if (value.importedName) lines.push(`const ${alias} = () => import('${importPath}').then((mod) => mod.${value.remoteName || 'default'});`);
lines.push(`const ${alias} = () => import('${importPath}').then((mod) => mod.${value.importedName + (value.importedNameProperty || '')});`);
else
lines.push(`const ${alias} = () => import('${importPath}').then((mod) => mod.default${value.importedNameProperty || ''});`);
} }
lines.push(`pwRegister({ ${[...componentRegistry.keys()].join(',\n ')} });`); lines.push(`__pwRegistry.initialize({ ${[...componentRegistry.keys()].join(',\n ')} });`);
return { return {
code: lines.join('\n'), code: lines.join('\n'),
map: { mappings: '' } map: { mappings: '' }
@ -418,3 +436,13 @@ function hasJSComponents(components: ComponentInfo[]): boolean {
} }
return false; return false;
} }
const importRegistryPrefix = `"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ImportRegistry = void 0;`;
const importRegistrySuffix = `exports.ImportRegistry = ImportRegistry;`;

View file

@ -14,33 +14,38 @@
* limitations under the License. * limitations under the License.
*/ */
import type { ImportRegistry } from '../src/importRegistry';
type JsonPrimitive = string | number | boolean | null; type JsonPrimitive = string | number | boolean | null;
type JsonValue = JsonPrimitive | JsonObject | JsonArray; type JsonValue = JsonPrimitive | JsonObject | JsonArray;
type JsonArray = JsonValue[]; type JsonArray = JsonValue[];
export type JsonObject = { [Key in string]?: JsonValue }; export type JsonObject = { [Key in string]?: JsonValue };
// JsxComponentChild can be anything, consider cases like: <>{1}</>, <>{null}</> export type ImportRef = {
export type JsxComponentChild = JsxComponent | string | number | boolean | null; __pw_type: 'importRef',
id: string,
property?: string,
};
export type JsxComponent = { export type JsxComponent = {
__pw_component_marker: true, __pw_type: 'jsx',
kind: 'jsx', type: any,
type: string,
props: Record<string, any>, props: Record<string, any>,
children?: JsxComponentChild[],
}; };
export type MountOptions = { export type MountOptions = {
props?: Record<string, any>,
slots?: Record<string, string | string[]>,
on?: Record<string, Function>,
hooksConfig?: any, hooksConfig?: any,
}; };
export type ObjectComponent = { export type ObjectComponentOptions = {
__pw_component_marker: true, props?: Record<string, any>;
kind: 'object', slots?: Record<string, string | string[]>;
type: string, on?: Record<string, Function>;
options?: MountOptions };
export type ObjectComponent = ObjectComponentOptions & {
__pw_type: 'object-component',
type: any,
}; };
export type Component = JsxComponent | ObjectComponent; export type Component = JsxComponent | ObjectComponent;
@ -56,5 +61,6 @@ declare global {
__pw_hooks_after_mount?: (<HooksConfig extends JsonObject = JsonObject>( __pw_hooks_after_mount?: (<HooksConfig extends JsonObject = JsonObject>(
params: { hooksConfig?: HooksConfig; [key: string]: any } params: { hooksConfig?: HooksConfig; [key: string]: any }
) => Promise<void>)[]; ) => Promise<void>)[];
__pwRegistry: ImportRegistry;
} }
} }

View file

@ -22,7 +22,7 @@ export interface MountOptions<HooksConfig extends JsonObject> {
hooksConfig?: HooksConfig; hooksConfig?: HooksConfig;
} }
interface MountResult extends Locator { export interface MountResult extends Locator {
unmount(): Promise<void>; unmount(): Promise<void>;
update(component: JSX.Element): Promise<void>; update(component: JSX.Element): Promise<void>;
} }

View file

@ -17,130 +17,48 @@
// @ts-check // @ts-check
// This file is injected into the registry as text, no dependencies are allowed. // This file is injected into the registry as text, no dependencies are allowed.
import * as __pwReact from 'react'; import __pwReact from 'react';
import { createRoot as __pwCreateRoot } from 'react-dom/client'; import { createRoot as __pwCreateRoot } from 'react-dom/client';
/** @typedef {import('../playwright-ct-core/types/component').JsxComponentChild} JsxComponentChild */
/** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */ /** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */
/** @typedef {import('react').FunctionComponent} FrameworkComponent */
/** @type {Map<string, () => Promise<FrameworkComponent>>} */
const __pwLoaderRegistry = new Map();
/** @type {Map<string, FrameworkComponent>} */
const __pwRegistry = new Map();
/** @type {Map<Element, import('react-dom/client').Root>} */ /** @type {Map<Element, import('react-dom/client').Root>} */
const __pwRootRegistry = new Map(); const __pwRootRegistry = new Map();
/**
* @param {Record<string, () => Promise<FrameworkComponent>>} components
*/
export function pwRegister(components) {
for (const [name, value] of Object.entries(components))
__pwLoaderRegistry.set(name, value);
}
/** /**
* @param {any} component * @param {any} component
* @returns {component is JsxComponent} * @returns {component is JsxComponent}
*/ */
function isComponent(component) { function isJsxComponent(component) {
return component.__pw_component_marker === true && component.kind === 'jsx'; return typeof component === 'object' && component && component.__pw_type === 'jsx';
} }
/** /**
* @param {JsxComponent | JsxComponentChild} component * @param {any} value
*/ */
async function __pwResolveComponent(component) { function __pwRender(value) {
if (!isComponent(component)) if (value === null || typeof value !== 'object')
return; return value;
if (isJsxComponent(value)) {
let componentFactory = __pwLoaderRegistry.get(component.type); const component = value;
if (!componentFactory) { const props = component.props ? __pwRender(component.props) : {};
// Lookup by shorthand. return __pwReact.createElement(/** @type { any } */ (component.type), { ...props, children: undefined }, props.children);
for (const [name, value] of __pwLoaderRegistry) {
if (component.type.endsWith(`_${name}`)) {
componentFactory = value;
break;
}
}
} }
if (Array.isArray(value)) {
if (!componentFactory && component.type[0].toUpperCase() === component.type[0]) const result = [];
throw new Error(`Unregistered component: ${component.type}. Following components are registered: ${[...__pwRegistry.keys()]}`); for (const item of value)
result.push(__pwRender(item));
if (componentFactory) return result;
__pwRegistry.set(component.type, await componentFactory());
if (component.children?.length)
await Promise.all(component.children.map(child => __pwResolveComponent(child)));
if (component.props)
await __resolveProps(component.props);
}
/**
* @param {Record<string, any>} props
*/
async function __resolveProps(props) {
for (const prop of Object.values(props)) {
if (Array.isArray(prop))
await Promise.all(prop.map(child => __pwResolveComponent(child)));
else if (isComponent(prop))
await __pwResolveComponent(prop);
else if (typeof prop === 'object' && prop !== null)
await __resolveProps(prop);
} }
} const result = {};
for (const [key, prop] of Object.entries(value))
/** result[key] = __pwRender(prop);
* @param {JsxComponentChild} child return result;
*/
function __renderChild(child) {
if (Array.isArray(child))
return child.map(grandChild => __renderChild(grandChild));
if (isComponent(child))
return __pwRender(child);
return child;
}
/**
* @param {Record<string, any>} props
*/
function __renderProps(props) {
const newProps = {};
for (const [key, prop] of Object.entries(props)) {
if (Array.isArray(prop))
newProps[key] = prop.map(child => __renderChild(child));
else if (isComponent(prop))
newProps[key] = __renderChild(prop);
else if (typeof prop === 'object' && prop !== null)
newProps[key] = __renderProps(prop);
else
newProps[key] = prop;
}
return newProps;
}
/**
* @param {JsxComponent} component
*/
function __pwRender(component) {
const componentFunc = __pwRegistry.get(component.type);
const props = __renderProps(component.props || {});
const children = component.children?.map(child => __renderChild(child)).filter(child => {
if (typeof child === 'string')
return !!child.trim();
return true;
});
const reactChildren = Array.isArray(children) && children.length === 1 ? children[0] : children;
return __pwReact.createElement(componentFunc || component.type, props, reactChildren);
} }
window.playwrightMount = async (component, rootElement, hooksConfig) => { window.playwrightMount = async (component, rootElement, hooksConfig) => {
if (component.kind !== 'jsx') if (!isJsxComponent(component))
throw new Error('Object mount notation is not supported'); throw new Error('Object mount notation is not supported');
await __pwResolveComponent(component);
let App = () => __pwRender(component); let App = () => __pwRender(component);
for (const hook of window.__pw_hooks_before_mount || []) { for (const hook of window.__pw_hooks_before_mount || []) {
const wrapper = await hook({ App, hooksConfig }); const wrapper = await hook({ App, hooksConfig });
@ -171,10 +89,9 @@ window.playwrightUnmount = async rootElement => {
}; };
window.playwrightUpdate = async (rootElement, component) => { window.playwrightUpdate = async (rootElement, component) => {
if (component.kind !== 'jsx') if (!isJsxComponent(component))
throw new Error('Object mount notation is not supported'); throw new Error('Object mount notation is not supported');
await __pwResolveComponent(component);
const root = __pwRootRegistry.get(rootElement); const root = __pwRootRegistry.get(rootElement);
if (root === undefined) if (root === undefined)
throw new Error('Component was not mounted'); throw new Error('Component was not mounted');

View file

@ -17,93 +17,45 @@
// @ts-check // @ts-check
// This file is injected into the registry as text, no dependencies are allowed. // This file is injected into the registry as text, no dependencies are allowed.
// Don't clash with the user land.
import __pwReact from 'react'; import __pwReact from 'react';
import __pwReactDOM from 'react-dom'; import __pwReactDOM from 'react-dom';
/** @typedef {import('../playwright-ct-core/types/component').JsxComponentChild} JsxComponentChild */
/** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */ /** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */
/** @typedef {import('react').FunctionComponent} FrameworkComponent */
/** @type {Map<string, () => Promise<FrameworkComponent>>} */
const __pwLoaderRegistry = new Map();
/** @type {Map<string, FrameworkComponent>} */
const __pwRegistry = new Map();
/**
* @param {{[key: string]: () => Promise<FrameworkComponent>}} components
*/
export function pwRegister(components) {
for (const [name, value] of Object.entries(components))
__pwLoaderRegistry.set(name, value);
}
/** /**
* @param {any} component * @param {any} component
* @returns {component is JsxComponent} * @returns {component is JsxComponent}
*/ */
function isComponent(component) { function isJsxComponent(component) {
return !(typeof component !== 'object' || Array.isArray(component)); return typeof component === 'object' && component && component.__pw_type === 'jsx';
} }
/** /**
* @param {JsxComponent | JsxComponentChild} component * @param {any} value
*/ */
async function __pwResolveComponent(component) { function __pwRender(value) {
if (!isComponent(component)) if (value === null || typeof value !== 'object')
return; return value;
if (isJsxComponent(value)) {
let componentFactory = __pwLoaderRegistry.get(component.type); const component = value;
if (!componentFactory) { const props = component.props ? __pwRender(component.props) : {};
// Lookup by shorthand. return __pwReact.createElement(/** @type { any } */ (component.type), { ...props, children: undefined }, props.children);
for (const [name, value] of __pwLoaderRegistry) {
if (component.type.endsWith(`_${name}`)) {
componentFactory = value;
break;
}
}
} }
if (Array.isArray(value)) {
if (!componentFactory && component.type[0].toUpperCase() === component.type[0]) const result = [];
throw new Error(`Unregistered component: ${component.type}. Following components are registered: ${[...__pwRegistry.keys()]}`); for (const item of value)
result.push(__pwRender(item));
if (componentFactory) return result;
__pwRegistry.set(component.type, await componentFactory()); }
const result = {};
if (component.children?.length) for (const [key, prop] of Object.entries(value))
await Promise.all(component.children.map(child => __pwResolveComponent(child))); result[key] = __pwRender(prop);
} return result;
/**
* @param {JsxComponentChild} child
*/
function __renderChild(child) {
if (Array.isArray(child))
return child.map(grandChild => __renderChild(grandChild));
if (isComponent(child))
return __pwRender(child);
return child;
}
/**
* @param {JsxComponent} component
*/
function __pwRender(component) {
const componentFunc = __pwRegistry.get(component.type);
const children = component.children?.map(child => __renderChild(child)).filter(child => {
if (typeof child === 'string')
return !!child.trim();
return true;
});
const reactChildren = Array.isArray(children) && children.length === 1 ? children[0] : children;
return __pwReact.createElement(componentFunc || component.type, component.props, reactChildren);
} }
window.playwrightMount = async (component, rootElement, hooksConfig) => { window.playwrightMount = async (component, rootElement, hooksConfig) => {
if (component.kind !== 'jsx') if (!isJsxComponent(component))
throw new Error('Object mount notation is not supported'); throw new Error('Object mount notation is not supported');
await __pwResolveComponent(component);
let App = () => __pwRender(component); let App = () => __pwRender(component);
for (const hook of window.__pw_hooks_before_mount || []) { for (const hook of window.__pw_hooks_before_mount || []) {
const wrapper = await hook({ App, hooksConfig }); const wrapper = await hook({ App, hooksConfig });
@ -123,9 +75,8 @@ window.playwrightUnmount = async rootElement => {
}; };
window.playwrightUpdate = async (rootElement, component) => { window.playwrightUpdate = async (rootElement, component) => {
if (component.kind !== 'jsx') if (!isJsxComponent(component))
throw new Error('Object mount notation is not supported'); throw new Error('Object mount notation is not supported');
await __pwResolveComponent(component);
__pwReactDOM.render(__pwRender(component), rootElement); __pwReactDOM.render(__pwRender(component), rootElement);
}; };

View file

@ -20,94 +20,62 @@
import { render as __pwSolidRender, createComponent as __pwSolidCreateComponent } from 'solid-js/web'; import { render as __pwSolidRender, createComponent as __pwSolidCreateComponent } from 'solid-js/web';
import __pwH from 'solid-js/h'; import __pwH from 'solid-js/h';
/** @typedef {import('../playwright-ct-core/types/component').JsxComponentChild} JsxComponentChild */
/** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */ /** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */
/** @typedef {() => import('solid-js').JSX.Element} FrameworkComponent */ /** @typedef {() => import('solid-js').JSX.Element} FrameworkComponent */
/** @type {Map<string, () => Promise<FrameworkComponent>>} */
const __pwLoaderRegistry = new Map();
/** @type {Map<string, FrameworkComponent>} */
const __pwRegistry = new Map();
/**
* @param {{[key: string]: () => Promise<FrameworkComponent>}} components
*/
export function pwRegister(components) {
for (const [name, value] of Object.entries(components))
__pwLoaderRegistry.set(name, value);
}
/** /**
* @param {any} component * @param {any} component
* @returns {component is JsxComponent} * @returns {component is JsxComponent}
*/ */
function isComponent(component) { function isJsxComponent(component) {
return !(typeof component !== 'object' || Array.isArray(component)); return typeof component === 'object' && component && component.__pw_type === 'jsx';
} }
/** /**
* @param {JsxComponent | JsxComponentChild} component * @param {any} child
*/
async function __pwResolveComponent(component) {
if (!isComponent(component))
return;
let componentFactory = __pwLoaderRegistry.get(component.type);
if (!componentFactory) {
// Lookup by shorthand.
for (const [name, value] of __pwLoaderRegistry) {
if (component.type.endsWith(`_${name}`)) {
componentFactory = value;
break;
}
}
}
if (!componentFactory && component.type[0].toUpperCase() === component.type[0])
throw new Error(`Unregistered component: ${component.type}. Following components are registered: ${[...__pwRegistry.keys()]}`);
if (componentFactory)
__pwRegistry.set(component.type, await componentFactory());
if (component.children?.length)
await Promise.all(component.children.map(child => __pwResolveComponent(child)));
}
/**
* @param {JsxComponentChild} child
*/ */
function __pwCreateChild(child) { function __pwCreateChild(child) {
if (Array.isArray(child)) if (Array.isArray(child))
return child.map(grandChild => __pwCreateChild(grandChild)); return child.map(grandChild => __pwCreateChild(grandChild));
if (isComponent(child)) if (isJsxComponent(child))
return __pwCreateComponent(child); return __pwCreateComponent(child);
return child; return child;
} }
/**
* @param {JsxComponent} component
* @returns {any[] | undefined}
*/
function __pwJsxChildArray(component) {
if (!component.props.children)
return;
if (Array.isArray(component.props.children))
return component.props.children;
return [component.props.children];
}
/** /**
* @param {JsxComponent} component * @param {JsxComponent} component
*/ */
function __pwCreateComponent(component) { function __pwCreateComponent(component) {
const componentFunc = __pwRegistry.get(component.type); const children = __pwJsxChildArray(component)?.map(child => __pwCreateChild(child)).filter(child => {
const children = component.children?.map(child => __pwCreateChild(child)).filter(child => {
if (typeof child === 'string') if (typeof child === 'string')
return !!child.trim(); return !!child.trim();
return true; return true;
}); });
if (!componentFunc) if (typeof component.type === 'string')
return __pwH(component.type, component.props, children); return __pwH(component.type, component.props, children);
return __pwSolidCreateComponent(componentFunc, { ...component.props, children }); return __pwSolidCreateComponent(component.type, { ...component.props, children });
} }
const __pwUnmountKey = Symbol('unmountKey'); const __pwUnmountKey = Symbol('unmountKey');
window.playwrightMount = async (component, rootElement, hooksConfig) => { window.playwrightMount = async (component, rootElement, hooksConfig) => {
if (component.kind !== 'jsx') if (!isJsxComponent(component))
throw new Error('Object mount notation is not supported'); throw new Error('Object mount notation is not supported');
await __pwResolveComponent(component);
let App = () => __pwCreateComponent(component); let App = () => __pwCreateComponent(component);
for (const hook of window.__pw_hooks_before_mount || []) { for (const hook of window.__pw_hooks_before_mount || []) {
const wrapper = await hook({ App, hooksConfig }); const wrapper = await hook({ App, hooksConfig });
@ -131,7 +99,7 @@ window.playwrightUnmount = async rootElement => {
}; };
window.playwrightUpdate = async (rootElement, component) => { window.playwrightUpdate = async (rootElement, component) => {
if (component.kind !== 'jsx') if (!isJsxComponent(component))
throw new Error('Object mount notation is not supported'); throw new Error('Object mount notation is not supported');
window.playwrightUnmount(rootElement); window.playwrightUnmount(rootElement);

View file

@ -25,50 +25,12 @@ import { detach as __pwDetach, insert as __pwInsert, noop as __pwNoop } from 'sv
/** @typedef {any} FrameworkComponent */ /** @typedef {any} FrameworkComponent */
/** @typedef {import('svelte').SvelteComponent} SvelteComponent */ /** @typedef {import('svelte').SvelteComponent} SvelteComponent */
/** @type {Map<string, () => Promise<FrameworkComponent>>} */
const __pwLoaderRegistry = new Map();
/** @type {Map<string, FrameworkComponent>} */
const __pwRegistry = new Map();
/**
* @param {{[key: string]: () => Promise<FrameworkComponent>}} components
*/
export function pwRegister(components) {
for (const [name, value] of Object.entries(components))
__pwLoaderRegistry.set(name, value);
}
/** /**
* @param {any} component * @param {any} component
* @returns {component is ObjectComponent} * @returns {component is ObjectComponent}
*/ */
function isComponent(component) { function isObjectComponent(component) {
return !(typeof component !== 'object' || Array.isArray(component)); return typeof component === 'object' && component && component.__pw_type === 'object-component';
}
/**
* @param {ObjectComponent} component
*/
async function __pwResolveComponent(component) {
if (!isComponent(component))
return;
let componentFactory = __pwLoaderRegistry.get(component.type);
if (!componentFactory) {
// Lookup by shorthand.
for (const [name, value] of __pwLoaderRegistry) {
if (component.type.endsWith(`_${name}_svelte`)) {
componentFactory = value;
break;
}
}
}
if (!componentFactory)
throw new Error(`Unregistered component: ${component.type}. Following components are registered: ${[...__pwRegistry.keys()]}`);
if (componentFactory)
__pwRegistry.set(component.type, await componentFactory());
} }
/** /**
@ -105,19 +67,19 @@ function __pwCreateSlots(slots) {
const __pwSvelteComponentKey = Symbol('svelteComponent'); const __pwSvelteComponentKey = Symbol('svelteComponent');
window.playwrightMount = async (component, rootElement, hooksConfig) => { window.playwrightMount = async (component, rootElement, hooksConfig) => {
if (component.kind !== 'object') if (!isObjectComponent(component))
throw new Error('JSX mount notation is not supported'); throw new Error('JSX mount notation is not supported');
await __pwResolveComponent(component); const objectComponent = component;
const componentCtor = __pwRegistry.get(component.type); const componentCtor = component.type;
class App extends componentCtor { class App extends componentCtor {
constructor(options = {}) { constructor(options = {}) {
super({ super({
target: rootElement, target: rootElement,
props: { props: {
...component.options?.props, ...objectComponent.props,
$$slots: __pwCreateSlots(component.options?.slots), $$slots: __pwCreateSlots(objectComponent.slots),
$$scope: {}, $$scope: {},
}, },
...options ...options
@ -134,7 +96,7 @@ window.playwrightMount = async (component, rootElement, hooksConfig) => {
rootElement[__pwSvelteComponentKey] = svelteComponent; rootElement[__pwSvelteComponentKey] = svelteComponent;
for (const [key, listener] of Object.entries(component.options?.on || {})) for (const [key, listener] of Object.entries(objectComponent.on || {}))
svelteComponent.$on(key, event => listener(event.detail)); svelteComponent.$on(key, event => listener(event.detail));
for (const hook of window.__pw_hooks_after_mount || []) for (const hook of window.__pw_hooks_after_mount || [])
@ -149,17 +111,16 @@ window.playwrightUnmount = async rootElement => {
}; };
window.playwrightUpdate = async (rootElement, component) => { window.playwrightUpdate = async (rootElement, component) => {
if (component.kind !== 'object') if (!isObjectComponent(component))
throw new Error('JSX mount notation is not supported'); throw new Error('JSX mount notation is not supported');
await __pwResolveComponent(component);
const svelteComponent = /** @type {SvelteComponent} */ (rootElement[__pwSvelteComponentKey]); const svelteComponent = /** @type {SvelteComponent} */ (rootElement[__pwSvelteComponentKey]);
if (!svelteComponent) if (!svelteComponent)
throw new Error('Component was not mounted'); throw new Error('Component was not mounted');
for (const [key, listener] of Object.entries(component.options?.on || {})) for (const [key, listener] of Object.entries(component.on || {}))
svelteComponent.$on(key, event => listener(event.detail)); svelteComponent.$on(key, event => listener(event.detail));
if (component.options?.props) if (component.props)
svelteComponent.$set(component.options.props); svelteComponent.$set(component.props);
}; };

View file

@ -22,69 +22,35 @@ import { compile as __pwCompile } from '@vue/compiler-dom';
import * as __pwVue from 'vue'; import * as __pwVue from 'vue';
/** @typedef {import('../playwright-ct-core/types/component').Component} Component */ /** @typedef {import('../playwright-ct-core/types/component').Component} Component */
/** @typedef {import('../playwright-ct-core/types/component').JsxComponentChild} JsxComponentChild */
/** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */ /** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */
/** @typedef {import('../playwright-ct-core/types/component').ObjectComponent} ObjectComponent */ /** @typedef {import('../playwright-ct-core/types/component').ObjectComponent} ObjectComponent */
/** @typedef {import('vue').Component} FrameworkComponent */ /** @typedef {import('vue').Component} FrameworkComponent */
/** @type {Map<string, () => Promise<FrameworkComponent>>} */ const __pwAllListeners = new Map();
const __pwLoaderRegistry = new Map();
/** @type {Map<string, FrameworkComponent>} */
const __pwRegistry = new Map();
/** /**
* @param {{[key: string]: () => Promise<FrameworkComponent>}} components * @param {any} component
* @returns {component is ObjectComponent}
*/ */
export function pwRegister(components) { function isObjectComponent(component) {
for (const [name, value] of Object.entries(components)) return typeof component === 'object' && component && component.__pw_type === 'object-component';
__pwLoaderRegistry.set(name, value);
} }
/** /**
* @param {any} component * @param {any} component
* @returns {component is Component} * @returns {component is JsxComponent}
*/ */
function isComponent(component) { function isJsxComponent(component) {
return !(typeof component !== 'object' || Array.isArray(component)); return typeof component === 'object' && component && component.__pw_type === 'jsx';
} }
/** /**
* @param {Component | JsxComponentChild} component * @param {any} child
*/
async function __pwResolveComponent(component) {
if (!isComponent(component))
return;
let componentFactory = __pwLoaderRegistry.get(component.type);
if (!componentFactory) {
// Lookup by shorthand.
for (const [name, value] of __pwLoaderRegistry) {
if (component.type.endsWith(`_${name}_vue`)) {
componentFactory = value;
break;
}
}
}
if (!componentFactory && component.type[0].toUpperCase() === component.type[0])
throw new Error(`Unregistered component: ${component.type}. Following components are registered: ${[...__pwRegistry.keys()]}`);
if (componentFactory)
__pwRegistry.set(component.type, await componentFactory());
if ('children' in component && component.children?.length)
await Promise.all(component.children.map(child => __pwResolveComponent(child)));
}
const __pwAllListeners = new Map();
/**
* @param {JsxComponentChild} child
*/ */
function __pwCreateChild(child) { function __pwCreateChild(child) {
if (Array.isArray(child)) if (Array.isArray(child))
return child.map(grandChild => __pwCreateChild(grandChild)); return child.map(grandChild => __pwCreateChild(grandChild));
if (isComponent(child)) if (isJsxComponent(child) || isObjectComponent(child))
return __pwCreateWrapper(child); return __pwCreateWrapper(child);
return child; return child;
} }
@ -132,14 +98,23 @@ function __pwSlotToFunction(slot) {
throw Error(`Invalid slot received.`); throw Error(`Invalid slot received.`);
} }
/**
* @param {JsxComponent} component
* @returns {any[] | undefined}
*/
function __pwJsxChildArray(component) {
if (!component.props.children)
return;
if (Array.isArray(component.props.children))
return component.props.children;
return [component.props.children];
}
/** /**
* @param {Component} component * @param {Component} component
*/ */
function __pwCreateComponent(component) { function __pwCreateComponent(component) {
let componentFunc = __pwRegistry.get(component.type); const isVueComponent = typeof component.type !== 'string';
componentFunc = componentFunc || component.type;
const isVueComponent = componentFunc !== component.type;
/** /**
* @type {(import('vue').VNode | string)[]} * @type {(import('vue').VNode | string)[]}
@ -151,12 +126,12 @@ function __pwCreateComponent(component) {
/** @type {{[key: string]: any}} */ /** @type {{[key: string]: any}} */
let props = {}; let props = {};
if (component.kind === 'jsx') { if (component.__pw_type === 'jsx') {
for (const child of component.children || []) { for (const child of __pwJsxChildArray(component) || []) {
if (typeof child !== 'string' && child.type === 'template' && child.kind === 'jsx') { if (isJsxComponent(child) && child.type === 'template') {
const slotProperty = Object.keys(child.props).find(k => k.startsWith('v-slot:')); const slotProperty = Object.keys(child.props).find(k => k.startsWith('v-slot:'));
const slot = slotProperty ? slotProperty.substring('v-slot:'.length) : 'default'; const slot = slotProperty ? slotProperty.substring('v-slot:'.length) : 'default';
slots[slot] = child.children?.map(__pwCreateChild); slots[slot] = __pwJsxChildArray(child)?.map(__pwCreateChild);
} else { } else {
children.push(__pwCreateChild(child)); children.push(__pwCreateChild(child));
} }
@ -175,16 +150,16 @@ function __pwCreateComponent(component) {
} }
} }
if (component.kind === 'object') { if (component.__pw_type === 'object-component') {
// Vue test util syntax. // Vue test util syntax.
for (const [key, value] of Object.entries(component.options?.slots || {})) { for (const [key, value] of Object.entries(component.slots || {})) {
if (key === 'default') if (key === 'default')
children.push(__pwSlotToFunction(value)); children.push(__pwSlotToFunction(value));
else else
slots[key] = __pwSlotToFunction(value); slots[key] = __pwSlotToFunction(value);
} }
props = component.options?.props || {}; props = component.props || {};
for (const [key, value] of Object.entries(component.options?.on || {})) for (const [key, value] of Object.entries(component.on || {}))
listeners[key] = value; listeners[key] = value;
} }
@ -197,7 +172,7 @@ function __pwCreateComponent(component) {
lastArg = children; lastArg = children;
} }
return { Component: componentFunc, props, slots: lastArg, listeners }; return { Component: component.type, props, slots: lastArg, listeners };
} }
function __pwWrapFunctions(slots) { function __pwWrapFunctions(slots) {
@ -248,7 +223,6 @@ const __pwAppKey = Symbol('appKey');
const __pwWrapperKey = Symbol('wrapperKey'); const __pwWrapperKey = Symbol('wrapperKey');
window.playwrightMount = async (component, rootElement, hooksConfig) => { window.playwrightMount = async (component, rootElement, hooksConfig) => {
await __pwResolveComponent(component);
const app = __pwCreateApp({ const app = __pwCreateApp({
render: () => { render: () => {
const wrapper = __pwCreateWrapper(component); const wrapper = __pwCreateWrapper(component);
@ -275,7 +249,6 @@ window.playwrightUnmount = async rootElement => {
}; };
window.playwrightUpdate = async (rootElement, component) => { window.playwrightUpdate = async (rootElement, component) => {
await __pwResolveComponent(component);
const wrapper = rootElement[__pwWrapperKey]; const wrapper = rootElement[__pwWrapperKey];
if (!wrapper) if (!wrapper)
throw new Error('Component was not mounted'); throw new Error('Component was not mounted');

View file

@ -21,67 +21,33 @@
import __pwVue, { h as __pwH } from 'vue'; import __pwVue, { h as __pwH } from 'vue';
/** @typedef {import('../playwright-ct-core/types/component').Component} Component */ /** @typedef {import('../playwright-ct-core/types/component').Component} Component */
/** @typedef {import('../playwright-ct-core/types/component').JsxComponentChild} JsxComponentChild */
/** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */ /** @typedef {import('../playwright-ct-core/types/component').JsxComponent} JsxComponent */
/** @typedef {import('../playwright-ct-core/types/component').ObjectComponent} ObjectComponent */ /** @typedef {import('../playwright-ct-core/types/component').ObjectComponent} ObjectComponent */
/** @typedef {import('vue').Component} FrameworkComponent */ /** @typedef {import('vue').Component} FrameworkComponent */
/** @type {Map<string, () => Promise<FrameworkComponent>>} */
const __pwLoaderRegistry = new Map();
/** @type {Map<string, FrameworkComponent>} */
const __pwRegistry = new Map();
/** /**
* @param {{[key: string]: () => Promise<FrameworkComponent>}} components * @param {any} component
* @returns {component is ObjectComponent}
*/ */
export function pwRegister(components) { function isObjectComponent(component) {
for (const [name, value] of Object.entries(components)) return typeof component === 'object' && component && component.__pw_type === 'object-component';
__pwLoaderRegistry.set(name, value);
} }
/** /**
* @param {any} component * @param {any} component
* @returns {component is Component} * @returns {component is JsxComponent}
*/ */
function isComponent(component) { function isJsxComponent(component) {
return !(typeof component !== 'object' || Array.isArray(component)); return typeof component === 'object' && component && component.__pw_type === 'jsx';
} }
/** /**
* @param {Component | JsxComponentChild} component * @param {any} child
*/
async function __pwResolveComponent(component) {
if (!isComponent(component))
return;
let componentFactory = __pwLoaderRegistry.get(component.type);
if (!componentFactory) {
// Lookup by shorthand.
for (const [name, value] of __pwLoaderRegistry) {
if (component.type.endsWith(`_${name}_vue`)) {
componentFactory = value;
break;
}
}
}
if (!componentFactory && component.type[0].toUpperCase() === component.type[0])
throw new Error(`Unregistered component: ${component.type}. Following components are registered: ${[...__pwRegistry.keys()]}`);
if (componentFactory)
__pwRegistry.set(component.type, await componentFactory());
if ('children' in component && component.children?.length)
await Promise.all(component.children.map(child => __pwResolveComponent(child)));
}
/**
* @param {Component | JsxComponentChild} child
*/ */
function __pwCreateChild(child) { function __pwCreateChild(child) {
if (Array.isArray(child)) if (Array.isArray(child))
return child.map(grandChild => __pwCreateChild(grandChild)); return child.map(grandChild => __pwCreateChild(grandChild));
if (isComponent(child)) if (isJsxComponent(child) || isObjectComponent(child))
return __pwCreateWrapper(child); return __pwCreateWrapper(child);
return child; return child;
} }
@ -94,18 +60,26 @@ function __pwCreateChild(child) {
* @return {boolean} * @return {boolean}
*/ */
function __pwComponentHasKeyInProps(Component, key) { function __pwComponentHasKeyInProps(Component, key) {
if (Array.isArray(Component.props)) return typeof Component.props === 'object' && Component.props && key in Component.props;
return Component.props.includes(key); }
return Object.entries(Component.props).flat().includes(key); /**
* @param {JsxComponent} component
* @returns {any[] | undefined}
*/
function __pwJsxChildArray(component) {
if (!component.props.children)
return;
if (Array.isArray(component.props.children))
return component.props.children;
return [component.props.children];
} }
/** /**
* @param {Component} component * @param {Component} component
*/ */
function __pwCreateComponent(component) { function __pwCreateComponent(component) {
const componentFunc = __pwRegistry.get(component.type) || component.type; const isVueComponent = typeof component.type !== 'string';
const isVueComponent = componentFunc !== component.type;
/** /**
* @type {(import('vue').VNode | string)[]} * @type {(import('vue').VNode | string)[]}
@ -119,12 +93,12 @@ function __pwCreateComponent(component) {
nodeData.scopedSlots = {}; nodeData.scopedSlots = {};
nodeData.on = {}; nodeData.on = {};
if (component.kind === 'jsx') { if (component.__pw_type === 'jsx') {
for (const child of component.children || []) { for (const child of __pwJsxChildArray(component) || []) {
if (typeof child !== 'string' && child.type === 'template' && child.kind === 'jsx') { if (isJsxComponent(child) && child.type === 'template') {
const slotProperty = Object.keys(child.props).find(k => k.startsWith('v-slot:')); const slotProperty = Object.keys(child.props).find(k => k.startsWith('v-slot:'));
const slot = slotProperty ? slotProperty.substring('v-slot:'.length) : 'default'; const slot = slotProperty ? slotProperty.substring('v-slot:'.length) : 'default';
nodeData.scopedSlots[slot] = () => child.children?.map(c => __pwCreateChild(c)); nodeData.scopedSlots[slot] = () => __pwJsxChildArray(child)?.map(c => __pwCreateChild(c));
} else { } else {
children.push(__pwCreateChild(child)); children.push(__pwCreateChild(child));
} }
@ -135,7 +109,7 @@ function __pwCreateComponent(component) {
const event = key.substring('v-on:'.length); const event = key.substring('v-on:'.length);
nodeData.on[event] = value; nodeData.on[event] = value;
} else { } else {
if (isVueComponent && __pwComponentHasKeyInProps(componentFunc, key)) if (isVueComponent && __pwComponentHasKeyInProps(component.type, key))
nodeData.props[key] = value; nodeData.props[key] = value;
else else
nodeData.attrs[key] = value; nodeData.attrs[key] = value;
@ -143,18 +117,17 @@ function __pwCreateComponent(component) {
} }
} }
if (component.kind === 'object') { if (component.__pw_type === 'object-component') {
// Vue test util syntax. // Vue test util syntax.
const options = component.options || {}; for (const [key, value] of Object.entries(component.slots || {})) {
for (const [key, value] of Object.entries(options.slots || {})) {
const list = (Array.isArray(value) ? value : [value]).map(v => __pwCreateChild(v)); const list = (Array.isArray(value) ? value : [value]).map(v => __pwCreateChild(v));
if (key === 'default') if (key === 'default')
children.push(...list); children.push(...list);
else else
nodeData.scopedSlots[key] = () => list; nodeData.scopedSlots[key] = () => list;
} }
nodeData.props = options.props || {}; nodeData.props = component.props || {};
for (const [key, value] of Object.entries(options.on || {})) for (const [key, value] of Object.entries(component.on || {}))
nodeData.on[key] = value; nodeData.on[key] = value;
} }
@ -167,7 +140,7 @@ function __pwCreateComponent(component) {
lastArg = children; lastArg = children;
} }
return { Component: componentFunc, nodeData, slots: lastArg }; return { Component: component.type, nodeData, slots: lastArg };
} }
/** /**
@ -184,7 +157,6 @@ const instanceKey = Symbol('instanceKey');
const wrapperKey = Symbol('wrapperKey'); const wrapperKey = Symbol('wrapperKey');
window.playwrightMount = async (component, rootElement, hooksConfig) => { window.playwrightMount = async (component, rootElement, hooksConfig) => {
await __pwResolveComponent(component);
let options = {}; let options = {};
for (const hook of window.__pw_hooks_before_mount || []) for (const hook of window.__pw_hooks_before_mount || [])
options = await hook({ hooksConfig, Vue: __pwVue }); options = await hook({ hooksConfig, Vue: __pwVue });
@ -213,7 +185,6 @@ window.playwrightUnmount = async rootElement => {
}; };
window.playwrightUpdate = async (element, options) => { window.playwrightUpdate = async (element, options) => {
await __pwResolveComponent(options);
const wrapper = /** @type {any} */(element)[wrapperKey]; const wrapper = /** @type {any} */(element)[wrapperKey];
if (!wrapper) if (!wrapper)
throw new Error('Component was not mounted'); throw new Error('Component was not mounted');

View file

@ -66,6 +66,7 @@ function babelTransformOptions(isTypeScript: boolean, isModule: boolean, plugins
// Support JSX/TSX at all times, regardless of the file extension. // Support JSX/TSX at all times, regardless of the file extension.
plugins.push([require('@babel/plugin-transform-react-jsx'), { plugins.push([require('@babel/plugin-transform-react-jsx'), {
throwIfNamespace: false,
runtime: 'automatic', runtime: 'automatic',
importSource: path.dirname(require.resolve('playwright')), importSource: path.dirname(require.resolve('playwright')),
}]); }]);

View file

@ -16,6 +16,7 @@
function jsx(type, props) { function jsx(type, props) {
return { return {
__pw_type: 'jsx',
type, type,
props, props,
}; };
@ -23,6 +24,7 @@ function jsx(type, props) {
function jsxs(type, props) { function jsxs(type, props) {
return { return {
__pw_type: 'jsx',
type, type,
props, props,
}; };

View file

@ -1,6 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5", "target": "ES2015",
"lib": [ "lib": [
"dom", "dom",
"dom.iterable", "dom.iterable",

View file

@ -523,11 +523,13 @@ test('should load jsx with top-level component', async ({ runInlineTest }) => {
const component = <div>Hello <span>world</span></div>; const component = <div>Hello <span>world</span></div>;
test('succeeds', () => { test('succeeds', () => {
expect(component).toEqual({ expect(component).toEqual({
__pw_type: 'jsx',
type: 'div', type: 'div',
props: { props: {
children: [ children: [
'Hello ', 'Hello ',
{ {
__pw_type: 'jsx',
type: 'span', type: 'span',
props: { props: {
children: 'world' children: 'world'

View file

@ -135,9 +135,8 @@ test('should extract component list', async ({ runInlineTest }, testInfo) => {
}); });
expect(metainfo.components).toEqual([{ expect(metainfo.components).toEqual([{
fullName: expect.stringContaining('playwright_test_src_button_tsx_Button'), id: expect.stringContaining('playwright_test_src_button_tsx_Button'),
importedName: 'Button', remoteName: 'Button',
importedNameProperty: '',
importPath: expect.stringContaining('button.tsx'), importPath: expect.stringContaining('button.tsx'),
isModuleOrAlias: false, isModuleOrAlias: false,
deps: [ deps: [
@ -145,9 +144,8 @@ test('should extract component list', async ({ runInlineTest }, testInfo) => {
expect.stringContaining('jsx-runtime.js'), expect.stringContaining('jsx-runtime.js'),
] ]
}, { }, {
fullName: expect.stringContaining('playwright_test_src_clashingNames1_tsx_ClashingName'), id: expect.stringContaining('playwright_test_src_clashingNames1_tsx_ClashingName'),
importedName: 'ClashingName', remoteName: 'ClashingName',
importedNameProperty: '',
importPath: expect.stringContaining('clashingNames1.tsx'), importPath: expect.stringContaining('clashingNames1.tsx'),
isModuleOrAlias: false, isModuleOrAlias: false,
deps: [ deps: [
@ -155,9 +153,8 @@ test('should extract component list', async ({ runInlineTest }, testInfo) => {
expect.stringContaining('jsx-runtime.js'), expect.stringContaining('jsx-runtime.js'),
] ]
}, { }, {
fullName: expect.stringContaining('playwright_test_src_clashingNames2_tsx_ClashingName'), id: expect.stringContaining('playwright_test_src_clashingNames2_tsx_ClashingName'),
importedName: 'ClashingName', remoteName: 'ClashingName',
importedNameProperty: '',
importPath: expect.stringContaining('clashingNames2.tsx'), importPath: expect.stringContaining('clashingNames2.tsx'),
isModuleOrAlias: false, isModuleOrAlias: false,
deps: [ deps: [
@ -165,9 +162,8 @@ test('should extract component list', async ({ runInlineTest }, testInfo) => {
expect.stringContaining('jsx-runtime.js'), expect.stringContaining('jsx-runtime.js'),
] ]
}, { }, {
fullName: expect.stringContaining('playwright_test_src_components_tsx_Component1'), id: expect.stringContaining('playwright_test_src_components_tsx_Component1'),
importedName: 'Component1', remoteName: 'Component1',
importedNameProperty: '',
importPath: expect.stringContaining('components.tsx'), importPath: expect.stringContaining('components.tsx'),
isModuleOrAlias: false, isModuleOrAlias: false,
deps: [ deps: [
@ -175,9 +171,8 @@ test('should extract component list', async ({ runInlineTest }, testInfo) => {
expect.stringContaining('jsx-runtime.js'), expect.stringContaining('jsx-runtime.js'),
] ]
}, { }, {
fullName: expect.stringContaining('playwright_test_src_components_tsx_Component2'), id: expect.stringContaining('playwright_test_src_components_tsx_Component2'),
importedName: 'Component2', remoteName: 'Component2',
importedNameProperty: '',
importPath: expect.stringContaining('components.tsx'), importPath: expect.stringContaining('components.tsx'),
isModuleOrAlias: false, isModuleOrAlias: false,
deps: [ deps: [
@ -185,9 +180,8 @@ test('should extract component list', async ({ runInlineTest }, testInfo) => {
expect.stringContaining('jsx-runtime.js'), expect.stringContaining('jsx-runtime.js'),
] ]
}, { }, {
fullName: expect.stringContaining('playwright_test_src_defaultExport_tsx'), id: expect.stringContaining('playwright_test_src_defaultExport_tsx'),
importPath: expect.stringContaining('defaultExport.tsx'), importPath: expect.stringContaining('defaultExport.tsx'),
importedNameProperty: '',
isModuleOrAlias: false, isModuleOrAlias: false,
deps: [ deps: [
expect.stringContaining('defaultExport.tsx'), expect.stringContaining('defaultExport.tsx'),
@ -497,9 +491,8 @@ test('should retain deps when test changes', async ({ runInlineTest }, testInfo)
const metainfo = JSON.parse(fs.readFileSync(testInfo.outputPath('playwright/.cache/metainfo.json'), 'utf-8')); const metainfo = JSON.parse(fs.readFileSync(testInfo.outputPath('playwright/.cache/metainfo.json'), 'utf-8'));
expect(metainfo.components).toEqual([{ expect(metainfo.components).toEqual([{
fullName: expect.stringContaining('playwright_test_src_button_tsx_Button'), id: expect.stringContaining('playwright_test_src_button_tsx_Button'),
importedName: 'Button', remoteName: 'Button',
importedNameProperty: '',
importPath: expect.stringContaining('button.tsx'), importPath: expect.stringContaining('button.tsx'),
isModuleOrAlias: false, isModuleOrAlias: false,
deps: [ deps: [

View file

@ -196,7 +196,7 @@ test('should work with stray JSX import', async ({ runInlineTest }) => {
expect(result.passed).toBe(1); expect(result.passed).toBe(1);
}); });
test.fixme('should work with stray JS import', async ({ runInlineTest }) => { test('should work with stray JS import', async ({ runInlineTest }) => {
const result = await runInlineTest({ const result = await runInlineTest({
'playwright.config.ts': playwrightConfig, 'playwright.config.ts': playwrightConfig,
'playwright/index.html': `<script type="module" src="./index.js"></script>`, 'playwright/index.html': `<script type="module" src="./index.js"></script>`,
@ -481,7 +481,7 @@ test('should normalize children', async ({ runInlineTest }) => {
import { OneChild, OtherComponent } from './component'; import { OneChild, OtherComponent } from './component';
test("can pass an HTML element to OneChild", async ({ mount }) => { test("can pass an HTML element to OneChild", async ({ mount }) => {
const component = await mount(<OneChild><p>child</p> </OneChild>); const component = await mount(<OneChild><p>child</p></OneChild>);
await expect(component).toHaveText("child"); await expect(component).toHaveText("child");
}); });