Skip to content

Commit

Permalink
cherry-pick(#28975): chore: refactor import processing in ct
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelfeldman committed Jan 18, 2024
1 parent 4d9f923 commit d47ed6a
Show file tree
Hide file tree
Showing 19 changed files with 436 additions and 621 deletions.
2 changes: 2 additions & 0 deletions packages/playwright-ct-core/src/DEPS.list
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[importRegistry.ts]
../types/**
59 changes: 59 additions & 0 deletions packages/playwright-ct-core/src/importRegistry.ts
Original file line number Diff line number Diff line change
@@ -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';
}
}
116 changes: 63 additions & 53 deletions packages/playwright-ct-core/src/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

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';

let boundCallbacksForMount: Function[] = [];
Expand All @@ -25,61 +25,65 @@ interface MountResult extends Locator {
update(options: Omit<MountOptions, 'hooksConfig'> | string | JsxComponent): Promise<void>;
}

export const fixtures: Fixtures<
PlaywrightTestArgs & PlaywrightTestOptions & {
mount: (component: any, options: any) => Promise<MountResult>;
},
PlaywrightWorkerArgs & PlaywrightWorkerOptions & { _ctWorker: { context: BrowserContext | undefined, hash: string } },
{ _contextFactory: (options?: BrowserContextOptions) => Promise<BrowserContext>, _contextReuseMode: ContextReuseMode }> = {
type TestFixtures = PlaywrightTestArgs & PlaywrightTestOptions & {
mount: (component: any, options: any) => Promise<MountResult>;
};
type WorkerFixtures = PlaywrightWorkerArgs & PlaywrightWorkerOptions & { _ctWorker: { context: BrowserContext | undefined, hash: string } };
type BaseTestFixtures = {
_contextFactory: (options?: BrowserContextOptions) => Promise<BrowserContext>,
_contextReuseMode: ContextReuseMode
};

export const fixtures: Fixtures<TestFixtures, WorkerFixtures, BaseTestFixtures> = {

_contextReuseMode: 'when-possible',

_contextReuseMode: 'when-possible',
serviceWorkers: 'block',

serviceWorkers: 'block',
_ctWorker: [{ context: undefined, hash: '' }, { scope: 'worker' }],

_ctWorker: [{ context: undefined, hash: '' }, { scope: 'worker' }],
page: async ({ page }, use, info) => {
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);
},

page: async ({ page }, use, info) => {
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!);
mount: async ({ page }, use) => {
await use(async (componentRef: JsxComponent | ImportRef, options?: ObjectComponentOptions & MountOptions) => {
const selector = await (page as any)._wrapApiCall(async () => {
return await innerMount(page, componentRef, options);
}, true);
await use(page);
},

mount: async ({ page }, use) => {
await use(async (component: JsxComponent | string, options?: MountOptions) => {
const selector = await (page as any)._wrapApiCall(async () => {
return await innerMount(page, component, 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 | Omit<MountOptions, 'hooksConfig'>) => {
if (isJsxApi(options))
return await innerUpdate(page, options);
await innerUpdate(page, component, options);
}
});
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 = [];
},
};
});
boundCallbacksForMount = [];
},
};

function isJsxApi(options: Record<string, unknown>): options is JsxComponent {
return options?.kind === 'jsx';
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> {
const component = createComponent(jsxOrType, options);
async function innerUpdate(page: Page, componentRef: JsxComponent | ImportRef, options: ObjectComponentOptions = {}): Promise<void> {
const component = createComponent(componentRef, options);
wrapFunctions(component, page, boundCallbacksForMount);

await page.evaluate(async ({ component }) => {
Expand All @@ -97,13 +101,14 @@ async function innerUpdate(page: Page, jsxOrType: JsxComponent | string, options
};

unwrapFunctions(component);
component = await window.__pwRegistry.resolveImports(component);
const rootElement = document.getElementById('root')!;
return await window.playwrightUpdate(rootElement, component);
}, { component });
}

async function innerMount(page: Page, jsxOrType: JsxComponent | string, options: MountOptions = {}): Promise<string> {
const component = createComponent(jsxOrType, options);
async function innerMount(page: Page, componentRef: JsxComponent | ImportRef, options: ObjectComponentOptions & MountOptions = {}): Promise<string> {
const component = createComponent(componentRef, options);
wrapFunctions(component, page, boundCallbacksForMount);

// WebKit does not wait for deferred scripts.
Expand All @@ -130,17 +135,22 @@ async function innerMount(page: Page, jsxOrType: JsxComponent | string, options:
rootElement.id = 'root';
document.body.appendChild(rootElement);
}

component = await window.__pwRegistry.resolveImports(component);
await window.playwrightMount(component, rootElement, hooksConfig);

return '#root >> internal:control=component';
}, { component, hooksConfig: options.hooksConfig });
return selector;
}

function createComponent(jsxOrType: JsxComponent | string, options: Omit<MountOptions, 'hooksConfig'> = {}): Component {
if (typeof jsxOrType !== 'string') return jsxOrType;
return { __pw_component_marker: true, kind: 'object', type: jsxOrType, options };
function createComponent(component: JsxComponent | ImportRef, options: ObjectComponentOptions = {}): Component {
if (component.__pw_type === 'jsx')
return component;
return {
__pw_type: 'object-component',
type: component,
...options,
};
}

function wrapFunctions(object: any, page: Page, callbacks: Function[]) {
Expand Down
Loading

0 comments on commit d47ed6a

Please sign in to comment.