Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat(test-runner): respect useDefineForClassFields from tsconfig (#43262)

Pavel Feldman063214f5ed4b
diff --git a/docs/src/test-typescript-js.md b/docs/src/test-typescript-js.md
index d607830af6..91946e8c6e 100644
--- a/docs/src/test-typescript-js.md
+++ b/docs/src/test-typescript-js.md
@@ -28,7 +28,7 @@ npx tsc -p tsconfig.json --noEmit -w
## tsconfig.json
-Playwright will pick up `tsconfig.json` for each source file it loads. Note that Playwright **only supports** the following tsconfig options: `allowJs`, `baseUrl`, `paths`, `jsx`, `jsxFactory`, `jsxFragmentFactory`, `jsxImportSource`, `references` and `extends`.
+Playwright will pick up `tsconfig.json` for each source file it loads. Note that Playwright **only supports** the following tsconfig options: `allowJs`, `baseUrl`, `paths`, `jsx`, `jsxFactory`, `jsxFragmentFactory`, `jsxImportSource`, `useDefineForClassFields`, `references` and `extends`. The `target` option is only used to determine `useDefineForClassFields`.
We recommend setting up a separate `tsconfig.json` in the tests directory so that you can change some preferences specifically for the tests. Here is an example directory structure.
@@ -86,6 +86,20 @@ Playwright compiles JSX in `.tsx` and `.jsx` files according to the `jsx`, `jsxF
}
```
+### tsconfig class fields
+
+Playwright compiles TypeScript class fields according to the `useDefineForClassFields` option in the `tsconfig.json`. Just like `tsc`, when it is not specified, it is enabled for `ES2022` and later targets, and when `target` is not specified.
+
+With `useDefineForClassFields` enabled, class fields follow the JavaScript semantics, so field initializers run before the constructor body and can not access constructor parameter properties. Disable it to keep the legacy TypeScript semantics.
+
+```json title="tsconfig.json"
+{
+ "compilerOptions": {
+ "useDefineForClassFields": false
+ }
+}
+```
+
### tsconfig resolution
By default, Playwright will look up a closest tsconfig for each imported file by going up the directory structure and looking for `tsconfig.json` or `jsconfig.json`. This way, you can create a `tests/tsconfig.json` file that will be used only for your tests and Playwright will pick it up automatically.
diff --git a/packages/playwright/src/transform/babelBundle.ts b/packages/playwright/src/transform/babelBundle.ts
index d2c7091ecf..1fdbf91481 100644
--- a/packages/playwright/src/transform/babelBundle.ts
+++ b/packages/playwright/src/transform/babelBundle.ts
@@ -36,7 +36,7 @@ export type JsxOptions = {
jsxFragmentFactory?: string;
jsxImportSource?: string;
};
-export type BabelTransformFunction = (code: string, filename: string, isModule: boolean, pluginsSuffix: BabelPlugin[], jsx?: JsxOptions) => BabelFileResult | null;
+export type BabelTransformFunction = (code: string, filename: string, isModule: boolean, pluginsSuffix: BabelPlugin[], useDefineForClassFields: boolean, jsx?: JsxOptions) => BabelFileResult | null;
const nodeMajorVersion = +process.versions.node.split('.')[0];
@@ -57,25 +57,29 @@ function jsxPlugin(jsx: JsxOptions | undefined): [any, any] {
}];
}
-function babelTransformOptions(isTypeScript: boolean, isModule: boolean, pluginsEpilogue: [string, any?][], jsx?: JsxOptions): TransformOptions {
+function babelTransformOptions(isTypeScript: boolean, isModule: boolean, pluginsEpilogue: [string, any?][], useDefineForClassFields: boolean, jsx?: JsxOptions): TransformOptions {
const plugins = [
[require('@babel/plugin-syntax-import-attributes'), { deprecatedAssertSyntax: true }],
];
if (isTypeScript) {
plugins.push(
- // Strip "declare" class fields before these plugins run:
+ // Strip "declare" class fields, and uninitialized ones that tsc omits without
+ // "useDefineForClassFields", before these plugins run:
// - plugin-proposal-decorators
// - plugin-transform-class-properties
// - plugin-transform-private-methods
// See https://github.com/microsoft/playwright/issues/38586
[
(): PluginObj => ({
- name: 'strip-declare-class-fields',
+ name: 'strip-type-only-class-fields',
visitor: {
Class(path) {
for (const member of path.get('body.body')) {
- if (member.isClassProperty() && member.node.declare)
+ if (!member.isClassProperty())
+ continue;
+ const { declare, value, decorators } = member.node;
+ if (declare || (!useDefineForClassFields && !value && !decorators?.length))
member.remove();
}
}
@@ -83,13 +87,20 @@ function babelTransformOptions(isTypeScript: boolean, isModule: boolean, plugins
})
],
[require('@babel/plugin-proposal-decorators'), { version: '2023-05' }],
- [require('@babel/plugin-transform-class-properties')],
+ );
+ // With "useDefineForClassFields", Node defines class fields natively.
+ if (!useDefineForClassFields) {
+ plugins.push(
+ [require('@babel/plugin-transform-class-properties')],
+ [require('@babel/plugin-transform-private-methods')],
+ );
+ }
+ plugins.push(
[require('@babel/plugin-transform-class-static-block')],
[require('@babel/plugin-transform-numeric-separator')],
[require('@babel/plugin-transform-logical-assignment-operators')],
[require('@babel/plugin-transform-nullish-coalescing-operator')],
[require('@babel/plugin-transform-optional-chaining')],
- [require('@babel/plugin-transform-private-methods')],
[require('@babel/plugin-syntax-json-strings')],
[require('@babel/plugin-syntax-optional-catch-binding')],
[require('@babel/plugin-syntax-async-generators')],
@@ -152,7 +163,7 @@ function babelTransformOptions(isTypeScript: boolean, isModule: boolean, plugins
setPublicClassFields: true,
},
presets: isTypeScript ? [
- [require('@babel/preset-typescript'), { onlyRemoveTypeImports: false }],
+ [require('@babel/preset-typescript'), { onlyRemoveTypeImports: false, allowDeclareFields: useDefineForClassFields }],
] : [],
plugins: [
...plugins,
@@ -169,14 +180,14 @@ function isTypeScript(filename: string) {
return filename.endsWith('.ts') || filename.endsWith('.tsx') || filename.endsWith('.mts') || filename.endsWith('.cts');
}
-export function babelTransform(code: string, filename: string, isModule: boolean, pluginsEpilogue: [string, any?][], jsx?: JsxOptions): BabelFileResult | null {
+export function babelTransform(code: string, filename: string, isModule: boolean, pluginsEpilogue: [string, any?][], useDefineForClassFields: boolean, jsx?: JsxOptions): BabelFileResult | null {
if (isTransforming)
return null;
// Prevent reentry while requiring plugins lazily.
isTransforming = true;
try {
- const options = babelTransformOptions(isTypeScript(filename), isModule, pluginsEpilogue, jsx);
+ const options = babelTransformOptions(isTypeScript(filename), isModule, pluginsEpilogue, useDefineForClassFields, jsx);
return babel.transform(code, { filename, ...options });
} finally {
isTransforming = false;
@@ -184,6 +195,6 @@ export function babelTransform(code: string, filename: string, isModule: boolean
}
export function babelParse(code: string, filename: string, isModule: boolean): babel.ParseResult {
- const options = babelTransformOptions(isTypeScript(filename), isModule, []);
+ const options = babelTransformOptions(isTypeScript(filename), isModule, [], true);
return babel.parse(code, { filename, ...options })!;
}
diff --git a/packages/playwright/src/transform/transform.ts b/packages/playwright/src/transform/transform.ts
index a889241bbf..ae1d8a3c72 100644
--- a/packages/playwright/src/transform/transform.ts
+++ b/packages/playwright/src/transform/transform.ts
@@ -41,6 +41,7 @@ type ParsedTsConfigData = {
paths: { key: string, values: string[] }[];
allowJs: boolean;
jsx?: JsxOptions;
+ useDefineForClassFields?: boolean;
};
const cachedTSConfigs = new Map<string, ParsedTsConfigData[]>();
@@ -86,9 +87,16 @@ function validateTsConfig(tsconfig: LoadedTsConfig): ParsedTsConfigData {
jsxFragmentFactory: tsconfig.jsxFragmentFactory,
jsxImportSource: tsconfig.jsxImportSource,
} : undefined,
+ useDefineForClassFields: tsconfig.useDefineForClassFields ?? (tsconfig.target ? targetUsesDefineForClassFields(tsconfig.target) : undefined),
};
}
+function targetUsesDefineForClassFields(target: string): boolean {
+ const normalized = target.toLowerCase();
+ const year = normalized.match(/^es(\d{4})$/)?.[1];
+ return normalized === 'esnext' || (!!year && +year >= 2022);
+}
+
function loadAndValidateTsconfigsForFile(file: string): ParsedTsConfigData[] {
if (_singleTSConfigPath && !_singleTSConfig)
_singleTSConfig = loadTsConfig(_singleTSConfigPath).map(validateTsConfig);
@@ -227,8 +235,11 @@ export function transformHook(originalCode: string, filename: string, moduleUrl?
process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE &&
process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some(f => filename.startsWith(f));
const pluginsEpilogue = hasPreprocessor ? [[process.env.PW_TEST_SOURCE_TRANSFORM!]] as BabelPlugin[] : [];
- const jsx = loadAndValidateTsconfigsForFile(filename).find(tsconfig => tsconfig.jsx)?.jsx;
- const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsEpilogue, jsx);
+ const tsconfigs = loadAndValidateTsconfigsForFile(filename);
+ const jsx = tsconfigs.find(tsconfig => tsconfig.jsx)?.jsx;
+ // Without "target", tsc defaults to the latest one, which defines class fields.
+ const useDefineForClassFields = tsconfigs.find(tsconfig => tsconfig.useDefineForClassFields !== undefined)?.useDefineForClassFields ?? true;
+ const hash = calculateHash(originalCode, filename, !!moduleUrl, pluginsEpilogue, useDefineForClassFields, jsx);
const { cachedCode, addToCache, serializedCache } = cc.getFromCompilationCache(filename, hash, moduleUrl);
if (cachedCode !== undefined)
return { code: cachedCode, serializedCache };
@@ -238,7 +249,7 @@ export function transformHook(originalCode: string, filename: string, moduleUrl?
process.env.BROWSERSLIST_IGNORE_OLD_DATA = 'true';
const { babelTransform }: { babelTransform: BabelTransformFunction } = require(libPath('transform', 'babelBundle'));
- const babelResult = babelTransform(originalCode, filename, !!moduleUrl, pluginsEpilogue, jsx);
+ const babelResult = babelTransform(originalCode, filename, !!moduleUrl, pluginsEpilogue, useDefineForClassFields, jsx);
if (!babelResult?.code)
return { code: originalCode, serializedCache };
const { code, map } = babelResult;
@@ -246,13 +257,14 @@ export function transformHook(originalCode: string, filename: string, moduleUrl?
return { code, serializedCache: added.serializedCache };
}
-function calculateHash(content: string, filePath: string, isModule: boolean, pluginsEpilogue: BabelPlugin[], jsx: JsxOptions | undefined): string {
+function calculateHash(content: string, filePath: string, isModule: boolean, pluginsEpilogue: BabelPlugin[], useDefineForClassFields: boolean, jsx: JsxOptions | undefined): string {
const hash = crypto.createHash('sha1')
.update(isModule ? 'esm' : 'no_esm')
.update(content)
.update(filePath)
.update(version)
.update(pluginsEpilogue.map(p => p[0]).join(','))
+ .update(useDefineForClassFields ? 'define' : 'assign')
.update(jsx ? JSON.stringify(jsx) : '')
.digest('hex');
return hash;
diff --git a/packages/playwright/src/transform/tsconfig-loader.ts b/packages/playwright/src/transform/tsconfig-loader.ts
index b9f71b5fad..ebbd21a214 100644
--- a/packages/playwright/src/transform/tsconfig-loader.ts
+++ b/packages/playwright/src/transform/tsconfig-loader.ts
@@ -41,6 +41,8 @@ interface TsConfig {
jsxFactory?: string;
jsxFragmentFactory?: string;
jsxImportSource?: string;
+ target?: string;
+ useDefineForClassFields?: boolean;
};
references?: { path: string }[];
}
@@ -57,6 +59,8 @@ export interface LoadedTsConfig {
jsxFactory?: string;
jsxFragmentFactory?: string;
jsxImportSource?: string;
+ target?: string;
+ useDefineForClassFields?: boolean;
}
const jsxOptionNames = ['jsx', 'jsxFactory', 'jsxFragmentFactory', 'jsxImportSource'] as const;
@@ -139,6 +143,10 @@ function innerLoadTsConfig(
if (parsedConfig.compilerOptions?.[name] !== undefined)
result[name] = parsedConfig.compilerOptions[name];
}
+ if (parsedConfig.compilerOptions?.target !== undefined)
+ result.target = parsedConfig.compilerOptions.target;
+ if (parsedConfig.compilerOptions?.useDefineForClassFields !== undefined)
+ result.useDefineForClassFields = parsedConfig.compilerOptions.useDefineForClassFields;
if (parsedConfig.compilerOptions?.paths !== undefined) {
// We must store pathsBasePath from the config that defines "paths" and later resolve
// based on this absolute path, when no "baseUrl" is specified. See tsc for reference:
diff --git a/tests/playwright-test/babel.spec.ts b/tests/playwright-test/babel.spec.ts
index e454c8410d..6d6c1bfa8b 100644
--- a/tests/playwright-test/babel.spec.ts
+++ b/tests/playwright-test/babel.spec.ts
@@ -110,6 +110,7 @@ test('should treat enums equally', async ({ runInlineTest }) => {
test('should be able to access |this| inside class properties', async ({ runInlineTest }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21794' });
const result = await runInlineTest({
+ 'tsconfig.json': `{ "compilerOptions": { "useDefineForClassFields": false } }`,
'example.spec.ts': `
import { test, expect } from '@playwright/test';
@@ -127,6 +128,45 @@ test('should be able to access |this| inside class properties', async ({ runInli
expect(result.passed).toBe(1);
});
+for (const [compilerOptions, define] of [
+ [{}, true],
+ [{ target: 'ES2022' }, true],
+ [{ target: 'ES2021' }, false],
+ [{ target: 'ES2021', useDefineForClassFields: true }, true],
+ [{ target: 'ESNext', useDefineForClassFields: false }, false],
+] as const) {
+ test(`should ${define ? 'define' : 'assign'} class fields with ${JSON.stringify(compilerOptions)}`, async ({ runInlineTest }) => {
+ const result = await runInlineTest({
+ 'tsconfig.json': JSON.stringify({ compilerOptions }),
+ 'example.spec.ts': `
+ import { test, expect } from '@playwright/test';
+
+ class Base {
+ redeclared = 'base';
+ setterCalls: string[] = [];
+ set overridden(value: string) { this.setterCalls.push(value); }
+ }
+
+ class Derived extends Base {
+ redeclared: string;
+ overridden = 'derived';
+ fromParameter = this.parameter + '-field';
+ constructor(private parameter: string) { super(); }
+ }
+
+ test('works', () => {
+ const derived = new Derived('parameter');
+ expect(derived.redeclared).toBe(${define ? 'undefined' : `'base'`});
+ expect(derived.setterCalls).toEqual(${define ? '[]' : `['derived']`});
+ expect(derived.fromParameter).toBe(${define ? `'undefined-field'` : `'parameter-field'`});
+ });
+ `,
+ });
+ expect(result.exitCode).toBe(0);
+ expect(result.passed).toBe(1);
+ });
+}
+
test('should work with |const| Type Parameters', async ({ runInlineTest }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/21900' });
const result = await runInlineTest({