From 0cad0de3e3fb29506a3f0d8844546fb0645b527a Mon Sep 17 00:00:00 2001 From: Joel Einbinder Date: Mon, 8 Nov 2021 16:25:40 -0500 Subject: [PATCH] fix(test runner): better error message when importing typescript from esmodule (#10061) --- packages/playwright-test/src/loader.ts | 8 ++++++++ tests/playwright-test/loader.spec.ts | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/packages/playwright-test/src/loader.ts b/packages/playwright-test/src/loader.ts index 32ef13d363..e281981bfb 100644 --- a/packages/playwright-test/src/loader.ts +++ b/packages/playwright-test/src/loader.ts @@ -208,6 +208,14 @@ export class Loader { } } } catch (error) { + if (error.code === 'ERR_MODULE_NOT_FOUND' && error.message.includes('Did you mean to import')) { + const didYouMean = /Did you mean to import (.*)\?/.exec(error.message)?.[1]; + if (didYouMean?.endsWith('.ts')) + throw errorWithFile(file, 'Cannot import a typescript file from an esmodule.'); + } + if (error.code === 'ERR_UNKNOWN_FILE_EXTENSION' && error.message.includes('.ts')) + throw errorWithFile(file, 'Cannot import a typescript file from an esmodule.'); + if (error instanceof SyntaxError && error.message.includes('Cannot use import statement outside a module')) throw errorWithFile(file, 'JavaScript files must end with .mjs to use import.'); diff --git a/tests/playwright-test/loader.spec.ts b/tests/playwright-test/loader.spec.ts index 72170f2d0e..4ad1ca69e8 100644 --- a/tests/playwright-test/loader.spec.ts +++ b/tests/playwright-test/loader.spec.ts @@ -215,3 +215,27 @@ test('should load esm config files', async ({ runInlineTest }) => { expect(result.exitCode).toBe(0); expect(result.passed).toBe(1); }); + +test('should fail to load ts from esm when package.json has type module', async ({ runInlineTest }) => { + const result = await runInlineTest({ + 'playwright.config.js': ` + //@no-header + import * as fs from 'fs'; + export default { projects: [{name: 'foo'}] }; + `, + 'package.json': JSON.stringify({ type: 'module' }), + 'a.test.js': ` + import { foo } from './b.ts'; + const { test } = pwt; + test('check project name', ({}, testInfo) => { + expect(testInfo.project.name).toBe('foo'); + }); + `, + 'b.ts': ` + export const foo: string = 'foo'; + ` + }); + + expect(result.exitCode).toBe(1); + expect(result.output).toContain('Cannot import a typescript file from an esmodule'); +});