Skip to content

Commit

Permalink
Added jest way of mocking ESM modules in test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
jpolavar committed Dec 18, 2024
1 parent 691fbd6 commit e809bc9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/require-ts-extension-imports.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ type StatSyncFn = (path: PathLike) => Stats;

jest.unstable_mockModule('fs', () => ({
default: {
existsSync: jest.fn(
(path) =>
typeof path === 'string' &&
(path.endsWith('bar') ||
path.endsWith('src/bar') ||
path.endsWith('bar-dir') ||
path.endsWith('services') ||
path.endsWith('.test')),
),
statSync: jest.fn<StatSyncFn>().mockImplementation(((path) => ({
isDirectory: () => typeof path === 'string' && (path.endsWith('bar-dir') || path.endsWith('services')),
})) as StatSyncFn),
Expand Down Expand Up @@ -66,5 +75,11 @@ createTester().run(ruleId, rule, {
output: `import type { ping } from '../../../services/index.ts';`,
name: 'Invalid import typing from directory without .ts extension',
},
{
code: `import { bar, foo, foo1 } from './test/bar.test';`,
errors: [{ messageId: 'REQUIRE-TS-EXTENSION-IMPORTS' }],
output: `import { bar, foo, foo1 } from './test/bar.test.ts';`,
name: 'Invalid import typing from test file without .ts extension',
},
],
});
7 changes: 6 additions & 1 deletion src/require-ts-extension-imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ const rule: ReturnType<typeof createRule> = createRule({
return {
ImportDeclaration(node: TSESTree.ImportDeclaration) {
const importPath = node.source.value;
if (importPath.startsWith('.') && !importPath.endsWith('.ts') && !importPath.endsWith('.json')) {
if (
importPath.startsWith('.') &&
!importPath.endsWith('.ts') &&
!importPath.endsWith('.json') &&
fs.existsSync(importPath)
) {
const absoluteImportPath = path.resolve(path.dirname(filename), importPath);
const stats = fs.statSync(absoluteImportPath);
const isDirectory = stats.isDirectory();
Expand Down

0 comments on commit e809bc9

Please sign in to comment.