Skip to content

Commit

Permalink
feat: ✨ testing 支持 mjs 文件 (#11818)
Browse files Browse the repository at this point in the history
  • Loading branch information
stormslowly authored Nov 2, 2023
1 parent e80e805 commit 352b0a8
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
3 changes: 3 additions & 0 deletions examples/test-test/utils/mjs.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function mjs() {
return 'mjs'
};
5 changes: 5 additions & 0 deletions examples/test-test/utils/mjs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import mjs from './mjs.mjs';

it('imports from mjs', () => {
expect(mjs()).toBe('mjs');
});
4 changes: 4 additions & 0 deletions packages/testing/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ export function createConfig(opts?: {
opts?.jsTransformer || 'esbuild',
opts?.jsTransformerOpts,
),
'^.+\\.mjs$': getJSTransformer(
opts?.jsTransformer || 'esbuild',
opts?.jsTransformerOpts,
),
},
moduleNameMapper: {
'^.+\\.(css|less|sass|scss|stylus)$':
Expand Down
18 changes: 16 additions & 2 deletions packages/testing/src/transformers/esbuild/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ const TS_TSX_REGEX = /\.tsx?$/;
const JS_JSX_REGEX = /\.jsx?$/;

function isTarget(path: string) {
return JS_JSX_REGEX.test(path) || TS_TSX_REGEX.test(path);
return (
JS_JSX_REGEX.test(path) || TS_TSX_REGEX.test(path) || path.endsWith('.mjs')
);
}

const createTransformer = (
Expand Down Expand Up @@ -70,7 +72,7 @@ const createTransformer = (
const result = transformSync(rawCode, {
...options,
...(config.globals['jest-esbuild'] as UserOptions),
loader: userOptions.loader || (extname(path).slice(1) as Loader),
loader: userOptions.loader || ext2Loader(extname(path)),
sourcefile: path,
sourcesContent: false,
});
Expand Down Expand Up @@ -100,6 +102,18 @@ const createTransformer = (
};
};

const EXT_MAP: Record<string, Loader> = {
'.js': 'js',
'.jsx': 'jsx',
'.ts': 'ts',
'.tsx': 'tsx',
'.mjs': 'js',
};

function ext2Loader(ext: string): Loader {
return EXT_MAP[ext] || 'js';
}

export default {
createTransformer,
};

0 comments on commit 352b0a8

Please sign in to comment.