Skip to content

Commit 1049d79

Browse files
committed
Modify unit test to compile ESM syntax
- Added function `pathsToESModuleNameMapper` to resolve relative import syntax with file extension. - Disabled ESLint rule 'import/no-extraneous-dependencies' for unit test files. - Appended file extenion `.js` for relative import in `main.spec.ts`.
1 parent 1bd2a59 commit 1049d79

File tree

3 files changed

+31
-5
lines changed

3 files changed

+31
-5
lines changed

.eslintrc.cjs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ const jestConfig = {
7979
],
8080
rules: {
8181
...tsConfig.rules,
82+
'import/no-extraneous-dependencies': 'off',
8283
'@typescript-eslint/no-non-null-assertion': 'off',
8384
},
8485
settings: tsConfig.settings,

jest.config.js

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,33 @@ import { pathsToModuleNameMapper } from 'ts-jest';
44
const require = createRequire(import.meta.url);
55
const { compilerOptions } = require('./tsconfig.json');
66

7+
/**
8+
* Enhance the Jest path mappings map returned from `pathsModuleNameMapper`
9+
* to support ES modules import syntax in TypeScript.
10+
*
11+
* @returns Jest path mappings map.
12+
*/
13+
function pathsToESMModuleNameMapper() {
14+
const map = pathsToModuleNameMapper(
15+
compilerOptions.paths,
16+
{ prefix: '<rootDir>' },
17+
);
18+
const esmMap = {};
19+
20+
Object.entries(map).forEach((entry) => {
21+
const [key, val] = entry;
22+
23+
if (/.*\(\.\*\)\$$/.test(key)) {
24+
const convertedKey = `${key.substring(0, key.length - 1)}\\.js$`;
25+
esmMap[convertedKey] = val;
26+
}
27+
28+
esmMap[key] = val;
29+
});
30+
31+
return esmMap;
32+
}
33+
734
export default {
835
testEnvironment: 'node',
936
globals: {
@@ -12,10 +39,7 @@ export default {
1239
},
1340
},
1441
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
15-
moduleNameMapper: pathsToModuleNameMapper(
16-
compilerOptions.paths,
17-
{ prefix: '<rootDir>/' },
18-
),
42+
moduleNameMapper: pathsToESMModuleNameMapper(),
1943
modulePathIgnorePatterns: [
2044
'<rootDir>/dist',
2145
'<rootDir>/node_modules',

tests/main/main.spec.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
import { jest } from '@jest/globals';
12
import { BrowserWindow } from 'electron';
2-
import { exportedForTests } from '_main/main';
3+
import { exportedForTests } from '_main/main.js';
34

45
jest.mock('electron', () => ({
56
app: {

0 commit comments

Comments
 (0)