-
Notifications
You must be signed in to change notification settings - Fork 247
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
base: main
Are you sure you want to change the base?
Changes from 10 commits
1d32972
9ce0a40
621b8da
c7d1901
fee7e7a
bf6127f
172594c
4fb2681
80063e6
a6782da
4fab92e
09da117
e92eb10
d60997c
36d37a3
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,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. | ||
| 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,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, | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| }); |
| 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'] }], | ||
|
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. can we add a few more tests for this option - we should have one for (I know you've already got at least one test covering the latter, but its still nice to have another) |
||
| ) { | ||
| 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' }; | ||
| } | ||
|
||
| } catch (err: any) { | ||
|
||
| // 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, | ||
| }); | ||
| } | ||
| }, | ||
| }; | ||
| }, | ||
| }); | ||
Uh oh!
There was an error while loading. Please reload this page.