-
Notifications
You must be signed in to change notification settings - Fork 248
feat: create new valid-mock-module-path rule
#1845
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
G-Rath
merged 17 commits into
jest-community:main
from
hainenber:feat/validate-mocked-module-path
Nov 20, 2025
Merged
Changes from 10 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
1d32972
feat(rule): add new rule to validate `jest.mock` path existence
hainenber 9ce0a40
chore: update rules.test.ts due to newly added rule
hainenber 621b8da
chore: rewrite implementation to return early when linting over unwan…
hainenber c7d1901
fix(ci): verify broken npmjs link in MD file by checking its `registr…
hainenber fee7e7a
build(dev-deps): update `markdown-link-check`
hainenber bf6127f
feat: apply suggestions from @G-Rath code review
hainenber 172594c
Revert "fix(ci): verify broken npmjs link in MD file by checking its …
hainenber 4fb2681
Revert "build(dev-deps): update `markdown-link-check`"
hainenber 80063e6
feat: change rule name + add tests + configurable module file extensi…
hainenber a6782da
Merge branch 'main' into feat/validate-mocked-module-path
hainenber 4fab92e
Apply suggestions from @G-Rath's code review
hainenber 09da117
Apply 2nd suggestion from @G-Rath
hainenber e92eb10
feat: recast err to `unknown` + refactor to return happy path asap
hainenber d60997c
chore: rerun `yarn regenerate-docs`
hainenber 36d37a3
Update src/rules/valid-mock-module-path.ts
hainenber cb5947e
feat(rule/valid-mock-module-path): add test to cover code branch that…
hainenber 8c9730b
chore: fix correct config to test `valid-mock-module-path` on eslint v9
hainenber File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| # Disallow mocking of non-existing module path (`valid-mock-module-path`) | ||
|
|
||
| <!-- end auto-generated rule header --> | ||
|
|
||
| This rule raises an error when using `jest.mock` and `jest.doMock` and the first | ||
| argument for mocked object (module/local file) do not exist. | ||
|
|
||
| ## Rule details | ||
|
|
||
| This rule checks existence of the supplied path for `jest.mock` or `jest.doMock` | ||
| in the first argument. | ||
|
|
||
| The following patterns are considered errors: | ||
|
|
||
| ```js | ||
| // Module(s) that cannot be found | ||
| jest.mock('@org/some-module-not-in-package-json'); | ||
| jest.mock('some-module-not-in-package-json'); | ||
|
|
||
| // Local module (directory) that cannot be found | ||
| jest.mock('../../this/module/does/not/exist'); | ||
|
|
||
| // Local file that cannot be found | ||
| jest.mock('../../this/path/does/not/exist.js'); | ||
| ``` | ||
|
|
||
| The following patterns are **not** considered errors: | ||
|
|
||
| ```js | ||
| // Module(s) that can be found | ||
| jest.mock('@org/some-module-in-package-json'); | ||
| jest.mock('some-module-in-package-json'); | ||
|
|
||
| // Local module that cannot be found | ||
| jest.mock('../../this/module/really/does/exist'); | ||
|
|
||
| // Local file that cannot be found | ||
| jest.mock('../../this/path/really/does/exist.js'); | ||
| ``` | ||
|
|
||
| ## Options | ||
|
|
||
| ```json | ||
| { | ||
| "jest/valid-mock-module-path": [ | ||
| "error", | ||
| { | ||
| "moduleFileExtensions": [".tsx", ".ts"] | ||
| } | ||
| ] | ||
| } | ||
| ``` | ||
|
|
||
| ### `moduleFileExtensions` | ||
|
|
||
| This array option controls which file extensions the plugin checks for | ||
| existence. Valid values are: | ||
hainenber marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| - `".js"` | ||
| - `".ts"` | ||
| - `".jsx"` | ||
| - `".tsx"` | ||
| - `".json"` | ||
|
|
||
| For any custom extension, a preceding dot **must** be present before the file | ||
| extension for desired effect. | ||
|
|
||
| The default value for this option is | ||
| `{ "moduleFileExtensions": [".js", ".ts", ".jsx", ".tsx", ".json"] }`. | ||
|
|
||
hainenber marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ## When Not To Use It | ||
|
|
||
| Don't use this rule on non-jest test files. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export const foo = 'foo_js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export const foo = 'foo_ts'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from './foo'; |
Empty file.
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import dedent from 'dedent'; | ||
| import rule from '../valid-mock-module-path'; | ||
| import { FlatCompatRuleTester as RuleTester, espreeParser } from './test-utils'; | ||
|
|
||
| const ruleTester = new RuleTester({ | ||
| parser: espreeParser, | ||
| parserOptions: { | ||
| ecmaVersion: 2015, | ||
| }, | ||
| }); | ||
|
|
||
| ruleTester.run('valid-mock-module-path', rule, { | ||
| valid: [ | ||
| { filename: __filename, code: 'jest.mock("./fixtures/module")' }, | ||
| { filename: __filename, code: 'jest.mock("./fixtures/module", () => {})' }, | ||
| { filename: __filename, code: 'jest.mock()' }, | ||
| { | ||
| filename: __filename, | ||
| code: 'jest.doMock("./fixtures/module", () => {})', | ||
| }, | ||
| { | ||
| filename: __filename, | ||
| code: dedent` | ||
| describe("foo", () => {}); | ||
| `, | ||
| }, | ||
| { filename: __filename, code: 'jest.doMock("./fixtures/module")' }, | ||
| { filename: __filename, code: 'jest.mock("./fixtures/module/foo.ts")' }, | ||
| { filename: __filename, code: 'jest.doMock("./fixtures/module/foo.ts")' }, | ||
| { filename: __filename, code: 'jest.mock("./fixtures/module/foo.js")' }, | ||
| { filename: __filename, code: 'jest.doMock("./fixtures/module/foo.js")' }, | ||
| 'jest.mock("eslint")', | ||
| 'jest.doMock("eslint")', | ||
| 'jest.mock("child_process")', | ||
| 'jest.mock(() => {})', | ||
| { | ||
| filename: __filename, | ||
| code: dedent` | ||
| const a = "../module/does/not/exist"; | ||
| jest.mock(a); | ||
| `, | ||
| }, | ||
| { filename: __filename, code: 'jest.mock("./fixtures/module/jsx/foo")' }, | ||
| { filename: __filename, code: 'jest.mock("./fixtures/module/tsx/foo")' }, | ||
| { | ||
| filename: __filename, | ||
| code: 'jest.mock("./fixtures/module/tsx/foo")', | ||
| options: [{ moduleFileExtensions: ['.jsx'] }], | ||
| }, | ||
| ], | ||
| invalid: [ | ||
| { | ||
| filename: __filename, | ||
| code: "jest.mock('../module/does/not/exist')", | ||
| errors: [ | ||
| { | ||
| messageId: 'invalidMockModulePath', | ||
| data: { moduleName: "'../module/does/not/exist'" }, | ||
| column: 1, | ||
| line: 1, | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| filename: __filename, | ||
| code: 'jest.mock("../file/does/not/exist.ts")', | ||
| errors: [ | ||
| { | ||
| messageId: 'invalidMockModulePath', | ||
| data: { moduleName: '"../file/does/not/exist.ts"' }, | ||
| column: 1, | ||
| line: 1, | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| filename: __filename, | ||
| code: 'jest.mock("./fixtures/module/foo.jsx")', | ||
| options: [{ moduleFileExtensions: ['.tsx'] }], | ||
| errors: [ | ||
| { | ||
| messageId: 'invalidMockModulePath', | ||
| data: { moduleName: '"./fixtures/module/foo.jsx"' }, | ||
| column: 1, | ||
| line: 1, | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| filename: __filename, | ||
| code: 'jest.mock("./fixtures/module/foo.jsx")', | ||
| options: [{ moduleFileExtensions: undefined }], | ||
| errors: [ | ||
| { | ||
| messageId: 'invalidMockModulePath', | ||
| data: { moduleName: '"./fixtures/module/foo.jsx"' }, | ||
| column: 1, | ||
| line: 1, | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| filename: __filename, | ||
| code: 'jest.mock("@doesnotexist/module")', | ||
| errors: [ | ||
| { | ||
| messageId: 'invalidMockModulePath', | ||
| data: { moduleName: '"@doesnotexist/module"' }, | ||
| column: 1, | ||
| line: 1, | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| import { statSync } from 'fs'; | ||
| import path from 'path'; | ||
| import { AST_NODE_TYPES, type TSESTree } from '@typescript-eslint/utils'; | ||
| import { | ||
| createRule, | ||
| findModuleName, | ||
| getAccessorValue, | ||
| isSupportedAccessor, | ||
| isTypeOfJestFnCall, | ||
| } from './utils'; | ||
|
|
||
| export default createRule< | ||
| [ | ||
| Partial<{ | ||
| moduleFileExtensions: readonly string[]; | ||
| }>, | ||
| ], | ||
| 'invalidMockModulePath' | ||
| >({ | ||
| name: __filename, | ||
| meta: { | ||
| type: 'problem', | ||
| docs: { | ||
| description: 'Disallow mocking of non-existing module path', | ||
hainenber marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| }, | ||
| messages: { | ||
| invalidMockModulePath: 'Module path {{ moduleName }} does not exist', | ||
| }, | ||
| schema: [ | ||
| { | ||
| type: 'object', | ||
| properties: { | ||
| moduleFileExtensions: { | ||
| type: 'array', | ||
| items: { type: 'string' }, | ||
| additionalItems: false, | ||
| }, | ||
| }, | ||
| additionalProperties: false, | ||
| }, | ||
| ], | ||
| }, | ||
| defaultOptions: [ | ||
| { | ||
| moduleFileExtensions: ['.js', '.ts', '.tsx', '.jsx', '.json'], | ||
| }, | ||
| ], | ||
| create( | ||
| context, | ||
| [{ moduleFileExtensions = ['.js', '.ts', '.tsx', '.jsx', '.json'] }], | ||
G-Rath marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) { | ||
| return { | ||
| CallExpression(node: TSESTree.CallExpression): void { | ||
| if (node.callee.type !== AST_NODE_TYPES.MemberExpression) { | ||
| return; | ||
| } | ||
|
|
||
| if ( | ||
| !node.arguments.length || | ||
| !isTypeOfJestFnCall(node, context, ['jest']) || | ||
| !( | ||
| isSupportedAccessor(node.callee.property) && | ||
| ['mock', 'doMock'].includes(getAccessorValue(node.callee.property)) | ||
| ) | ||
| ) { | ||
| return; | ||
| } | ||
|
|
||
| const moduleName = findModuleName(node.arguments[0]); | ||
|
|
||
| if (!moduleName) { | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| if (!moduleName.value.startsWith('.')) { | ||
| require.resolve(moduleName.value); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| const resolvedModulePath = path.resolve( | ||
| path.dirname(context.filename), | ||
| moduleName.value, | ||
| ); | ||
|
|
||
| const hasPossiblyModulePaths = ['', ...moduleFileExtensions].some( | ||
| ext => { | ||
| try { | ||
| statSync(`${resolvedModulePath}${ext}`); | ||
|
|
||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| }, | ||
| ); | ||
|
|
||
| if (!hasPossiblyModulePaths) { | ||
| throw { code: 'MODULE_NOT_FOUND' }; | ||
| } | ||
G-Rath marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } catch (err: any) { | ||
G-Rath marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // Reports unexpected issues when attempt to verify mocked module path. | ||
| // The list of possible errors is non-exhaustive. | ||
| /* istanbul ignore if */ | ||
| if (!['MODULE_NOT_FOUND', 'ENOENT'].includes(err.code)) { | ||
| throw new Error( | ||
| `Error when trying to validate mock module path from \`jest.mock\`: ${err}`, | ||
| ); | ||
| } | ||
|
|
||
| context.report({ | ||
| messageId: 'invalidMockModulePath', | ||
| data: { moduleName: moduleName.raw }, | ||
| node, | ||
| }); | ||
| } | ||
| }, | ||
| }; | ||
| }, | ||
| }); | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.