-
Notifications
You must be signed in to change notification settings - Fork 243
feat(rule): add new rule to validate jest.mock path existence
#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
base: main
Are you sure you want to change the base?
Changes from all commits
1d32972
9ce0a40
621b8da
c7d1901
fee7e7a
bf6127f
172594c
4fb2681
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Disallow mocking of non-existing module path (`valid-mocked-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'); | ||
| ``` | ||
|
|
||
| ## When Not To Use It | ||
|
|
||
| Don't use this rule on non-jest test files. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export const foo = 'foo_js'; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export const foo = 'foo_ts'; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from './foo'; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| import dedent from 'dedent'; | ||
| import rule from '../valid-mocked-module-path'; | ||
| import { FlatCompatRuleTester as RuleTester, espreeParser } from './test-utils'; | ||
|
|
||
| const ruleTester = new RuleTester({ | ||
| parser: espreeParser, | ||
| parserOptions: { | ||
| ecmaVersion: 2015, | ||
| }, | ||
| }); | ||
|
|
||
| ruleTester.run('valid-mocked-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")', | ||
| ], | ||
| 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("@doesnotexist/module")', | ||
| errors: [ | ||
| { | ||
| messageId: 'invalidMockModulePath', | ||
| data: { moduleName: '"@doesnotexist/module"' }, | ||
| column: 1, | ||
| line: 1, | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| 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({ | ||
| name: __filename, | ||
| meta: { | ||
| type: 'problem', | ||
| docs: { | ||
| description: 'Disallow mocking of non-existing module path', | ||
| }, | ||
| messages: { | ||
| invalidMockModulePath: 'Module path {{ moduleName }} does not exist', | ||
| }, | ||
| schema: [], | ||
| }, | ||
| defaultOptions: [], | ||
| create(context) { | ||
| return { | ||
| CallExpression(node: TSESTree.CallExpression): void { | ||
| const { callee } = node; | ||
|
|
||
| if (callee.type !== AST_NODE_TYPES.MemberExpression) { | ||
| return; | ||
| } | ||
|
|
||
| const { property } = callee; | ||
|
|
||
| if ( | ||
| !node.arguments.length || | ||
| !isTypeOfJestFnCall(node, context, ['jest']) || | ||
| !( | ||
| isSupportedAccessor(property) && | ||
| ['mock', 'doMock'].includes(getAccessorValue(property)) | ||
| ) | ||
| ) { | ||
| return; | ||
| } | ||
|
|
||
| const moduleName = findModuleName(node.arguments[0]); | ||
|
|
||
| /* istanbul ignore if */ | ||
| if (!moduleName) { | ||
| throw new Error( | ||
| 'Cannot parse mocked module name from `jest.mock` - - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`', | ||
| ); | ||
| } | ||
|
Comment on lines
+50
to
+54
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is a very possible path as the requirement is "something other than a string is passed as the first argument", which includes variables but also silly stuff like an inline function (i.e. |
||
|
|
||
| try { | ||
| if (moduleName.value.startsWith('.')) { | ||
| const resolvedModulePath = path.resolve( | ||
| path.dirname(context.filename), | ||
| moduleName.value, | ||
| ); | ||
|
|
||
| const hasPossiblyModulePaths = ['', '.js', '.ts'] | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should probably be configurable, and I'm 98% sure this is related to (technically @SimenB can you confirm if I'm right? |
||
| .map(ext => `${resolvedModulePath}${ext}`) | ||
| .some(modPath => { | ||
| try { | ||
| statSync(modPath); | ||
|
|
||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| }); | ||
|
|
||
| if (!hasPossiblyModulePaths) { | ||
| throw { code: 'MODULE_NOT_FOUND' }; | ||
| } | ||
| } else { | ||
| require.resolve(moduleName.value); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we can do an early return to avoid this |
||
| } | ||
| } catch (err: any) { | ||
| // Skip over any 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)) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think we should be swallowing all other errors like this - we should either report or rethrow. The two situations I can think of where we'd have an error is a bug in our code, or an issue with accessing the path. Ideally for the former we'd want to rethrow, but the latter we probably want to report since its reasonable to expect Jest itself would have the same error - unfortunately I don't think we can reliably distinguish those situations so we probably just need to pick one action and change it later if it turns out to be noisy
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Okay so I think I'll change the code to rethrow unexpected errors since there are only |
||
| return; | ||
| } | ||
|
|
||
| context.report({ | ||
| messageId: 'invalidMockModulePath', | ||
| data: { moduleName: moduleName.raw }, | ||
| node, | ||
| }); | ||
| } | ||
| }, | ||
| }; | ||
| }, | ||
| }); | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: I don't think it's worth destructing this or
propertyinto variables given they're only used a couple of times