Skip to content

Commit

Permalink
fix(test runner): do not use @babel/plugin-transform-dynamic-import (
Browse files Browse the repository at this point in the history
…#31285)

Historically, this plugin was important to translate dynamic imports
into require calls so that we can intercept them and transpile.

This is not needed anymore with ESM loader enabled by default, so we can
avoid this transformation and support dynamic imports of ESM-only
packages/files.

Fixes #17075, fixes #23255, fixes #31140, references #23662.
  • Loading branch information
dgozman authored Jun 13, 2024
1 parent e828536 commit b9106a4
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 104 deletions.
13 changes: 0 additions & 13 deletions docs/src/test-typescript-js.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,3 @@ In `package.json`, add two scripts:
The `pretest` script runs typescript on the tests. `test` will run the tests that have been generated to the `tests-out` directory. The `-c` argument configures the test runner to look for tests inside the `tests-out` directory.

Then `npm run test` will build the tests and run them.

## Using `import` inside `evaluate()`

Using dynamic imports inside a function passed to various `evaluate()` methods is not supported. This is because Playwright uses `Function.prototype.toString()` to serialize functions, and transpiler will sometimes replace dynamic imports with `require()` calls, which are not valid inside the web page.

To work around this issue, use a string template instead of a function:

```js
await page.evaluate(`(async () => {
const { value } = await import('some-module');
console.log(value);
})()`);
```
58 changes: 1 addition & 57 deletions packages/playwright/ThirdPartyNotices.txt
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ This project incorporates components from the projects listed below. The origina
- @babel/[email protected] (https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-async-generators)
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-dynamic-import)
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-export-namespace-from)
- @babel/[email protected] (https://github.com/babel/babel)
Expand All @@ -54,7 +53,6 @@ This project incorporates components from the projects listed below. The origina
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel)
- @babel/[email protected] (https://github.com/babel/babel)
Expand Down Expand Up @@ -1252,33 +1250,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF @babel/[email protected] AND INFORMATION

%% @babel/[email protected] NOTICES AND INFORMATION BEGIN HERE
=========================================
MIT License

Copyright (c) 2014-present Sebastian McKenzie and other contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF @babel/[email protected] AND INFORMATION

%% @babel/[email protected] NOTICES AND INFORMATION BEGIN HERE
=========================================
MIT License
Expand Down Expand Up @@ -1684,33 +1655,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF @babel/[email protected] AND INFORMATION

%% @babel/[email protected] NOTICES AND INFORMATION BEGIN HERE
=========================================
MIT License

Copyright (c) 2014-present Sebastian McKenzie and other contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF @babel/[email protected] AND INFORMATION

%% @babel/[email protected] NOTICES AND INFORMATION BEGIN HERE
=========================================
MIT License
Expand Down Expand Up @@ -4461,6 +4405,6 @@ END OF [email protected] AND INFORMATION

SUMMARY BEGIN HERE
=========================================
Total Packages: 153
Total Packages: 151
=========================================
END OF SUMMARY
27 changes: 0 additions & 27 deletions packages/playwright/bundles/babel/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/playwright/bundles/babel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
"@babel/plugin-syntax-optional-catch-binding": "^7.8.3",
"@babel/plugin-transform-class-properties": "^7.24.1",
"@babel/plugin-transform-class-static-block": "^7.24.4",
"@babel/plugin-transform-dynamic-import": "^7.24.1",
"@babel/plugin-transform-export-namespace-from": "^7.24.1",
"@babel/plugin-transform-logical-assignment-operators": "^7.24.1",
"@babel/plugin-transform-modules-commonjs": "^7.24.1",
Expand Down
5 changes: 3 additions & 2 deletions packages/playwright/bundles/babel/src/babelBundleImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,9 @@ function babelTransformOptions(isTypeScript: boolean, isModule: boolean, plugins

if (!isModule) {
plugins.push([require('@babel/plugin-transform-modules-commonjs')]);
// This converts async imports to require() calls so that we can intercept them with pirates.
plugins.push([require('@babel/plugin-transform-dynamic-import')]);
// Note: we used to include '@babel/plugin-transform-dynamic-import' to convert async imports
// into require(), so that pirates can intercept them. With the ESM loader enabled by default,
// there is no need for this.
plugins.push([
(): PluginObj => ({
name: 'css-to-identity-obj-proxy',
Expand Down
9 changes: 7 additions & 2 deletions packages/playwright/src/transform/esmLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import url from 'url';
import { addToCompilationCache, currentFileDepsCollector, serializeCompilationCache, startCollectingFileDeps, stopCollectingFileDeps } from './compilationCache';
import { transformHook, resolveHook, setTransformConfig, shouldTransform } from './transform';
import { PortTransport } from './portTransport';
import { fileIsModule } from '../util';

// Node < 18.6: defaultResolve takes 3 arguments.
// Node >= 18.6: nextResolve from the chain takes 2 arguments.
Expand Down Expand Up @@ -62,9 +63,13 @@ async function load(moduleUrl: string, context: { format?: string }, defaultLoad
if (transformed.serializedCache)
await transport?.send('pushToCompilationCache', { cache: transformed.serializedCache });

// Output format is always the same as input format, if it was unknown, we always report modules.
// Output format is required, so we determine it manually when unknown.
// shortCircuit is required by Node >= 18.6 to designate no more loaders should be called.
return { format: context.format || 'module', source: transformed.code, shortCircuit: true };
return {
format: context.format || (fileIsModule(filename) ? 'module' : 'commonjs'),
source: transformed.code,
shortCircuit: true,
};
}

let transport: PortTransport | undefined;
Expand Down
54 changes: 52 additions & 2 deletions tests/playwright-test/loader.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -961,29 +961,79 @@ test('should complain when one test file imports another', async ({ runInlineTes
expect(result.output).toContain(`test file "a.test.ts" should not import test file "b.test.ts"`);
});

test('should support dynamic import', async ({ runInlineTest }) => {
test('should support dynamic imports of js, ts from js, ts and cjs', async ({ runInlineTest }) => {
const result = await runInlineTest({
'helper.ts': `
module.exports.foo = 'foo';
`,
'helper2.ts': `
module.exports.bar = 'bar';
`,
'helper3.js': `
module.exports.baz = 'baz';
`,
'passthrough.cjs': `
module.exports.load = () => import('./helper2');
`,
'a.test.ts': `
import { test, expect } from '@playwright/test';
test('pass', async () => {
const { foo } = await import('./helper');
expect(foo).toBe('foo');
const { baz } = await import('./helper3');
expect(baz).toBe('baz');
});
`,
'b.test.ts': `
import { test, expect } from '@playwright/test';
import { load } from './passthrough.cjs';
test('pass', async () => {
const { foo } = await import('./helper');
expect(foo).toBe('foo');
const { bar } = await load();
expect(bar).toBe('bar');
});
`,
'c.test.js': `
import { test, expect } from '@playwright/test';
test('pass', async () => {
const { foo } = await import('./helper');
expect(foo).toBe('foo');
});
`,
}, { workers: 1 });
expect(result.passed).toBe(2);
expect(result.passed).toBe(3);
expect(result.exitCode).toBe(0);
});

test('should support dynamic imports of esm-only packages', async ({ runInlineTest }) => {
const result = await runInlineTest({
'node_modules/foo-pkg/package.json': `
{
"name": "foo-pkg",
"type": "module",
"exports": { "default": "./index.js" }
}
`,
'node_modules/foo-pkg/index.js': `
export const foo = 'bar';
`,
'package.json': `{ "name": "test-project" }`,
'a.test.ts': `
import { test, expect } from '@playwright/test';
test('pass', async () => {
const { foo } = await import('foo-pkg');
expect(foo).toBe('bar');
});
`,
}, { workers: 1 });
expect(result.passed).toBe(1);
expect(result.exitCode).toBe(0);
});

Expand Down
24 changes: 24 additions & 0 deletions tests/playwright-test/playwright.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -848,3 +848,27 @@ test('should explain a failure when using a dispose APIRequestContext', async ({
expect(result.passed).toBe(0);
expect(result.output).toContain(`Recommended fix: use a separate { request } in the test`);
});

test('should allow dynamic import in evaluate', async ({ runInlineTest, server }) => {
server.setRoute('/foo.js', (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/javascript' }).end(`
export const foo = 'bar';
`);
});
const result = await runInlineTest({
'a.test.ts': `
import { test, expect } from '@playwright/test';
test('test', async ({ page }) => {
await page.goto("${server.EMPTY_PAGE}");
const result = await page.evaluate(async () => {
const { foo } = await import("${server.PREFIX + '/foo.js'}");
return foo;
});
expect(result).toBe('bar');
});
`,
}, { workers: 1 });
expect(result.exitCode).toBe(0);
expect(result.passed).toBe(1);
});

0 comments on commit b9106a4

Please sign in to comment.