Skip to content

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

fix(ct): detect React import after closing brace in minified code (#38956)

Yury Semikhatsky84f4f8895acb
diff --git a/packages/playwright-ct-core/src/viteUtils.ts b/packages/playwright-ct-core/src/viteUtils.ts
index f73d9e09cb..86f5ea6e1b 100644
--- a/packages/playwright-ct-core/src/viteUtils.ts
+++ b/packages/playwright-ct-core/src/viteUtils.ts
@@ -164,7 +164,7 @@ export function hasJSComponents(components: ImportInfo[]): boolean {
return false;
}
-const importReactRE = /(^|\n|;)import\s+(\*\s+as\s+)?React(,|\s+)/;
+const importReactRE = /(^|[\n;}\])])import\s+(\*\s+as\s+)?React(,|\s+)/;
const compiledReactRE = /(const|var)\s+React\s*=/;
const runtimeImportRequire = /import\(['"`]react['"`]\)|require\(['"`]react['"`]\)/i;
diff --git a/tests/playwright-test/playwright.ct-react.spec.ts b/tests/playwright-test/playwright.ct-react.spec.ts
index a5a545347d..dec391284b 100644
--- a/tests/playwright-test/playwright.ct-react.spec.ts
+++ b/tests/playwright-test/playwright.ct-react.spec.ts
@@ -597,6 +597,36 @@ test('should allow import from shared file', async ({ runInlineTest }) => {
expect(result.passed).toBe(1);
});
+test('should not add React import to minified .js file that already imports React after closing brace', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/38906' }
+}, async ({ runInlineTest }) => {
+ const result = await runInlineTest({
+ 'playwright.config.ts': playwrightCtConfigText,
+ 'playwright/index.html': `<script type="module" src="./index.js"></script>`,
+ 'playwright/index.js': ``,
+
+ 'src/minified-component.js': `function foo(){return 1}import React from 'react';export const MinifiedComponent = () => React.createElement('div', null, 'Minified');`,
+
+ 'src/button.jsx': `
+ import { MinifiedComponent } from './minified-component';
+ export const Button = () => <MinifiedComponent />;
+ `,
+
+ 'src/button.test.jsx': `
+ import { test, expect } from '@playwright/experimental-ct-react';
+ import { Button } from './button';
+
+ test('pass', async ({ mount }) => {
+ const component = await mount(<Button></Button>);
+ await expect(component).toHaveText('Minified');
+ });
+ `,
+ }, { workers: 1 });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.passed).toBe(1);
+});
+
test('should throw test error when template index.html is not provided', async ({ runInlineTest }) => {
const result = await runInlineTest({
'playwright.config.ts': `