fix(test runner): better error message when importing typescript from esmodule (#10061)

This commit is contained in:
Joel Einbinder 2021-11-08 16:25:40 -05:00 committed by GitHub
parent 0a104bc500
commit 0cad0de3e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 0 deletions

View File

@ -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.');

View File

@ -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');
});