diff --git a/packages/eslint-plugin/src/rules/dependency-checks.spec.ts b/packages/eslint-plugin/src/rules/dependency-checks.spec.ts index e856a7834d917..1f304acbeeeb3 100644 --- a/packages/eslint-plugin/src/rules/dependency-checks.spec.ts +++ b/packages/eslint-plugin/src/rules/dependency-checks.spec.ts @@ -916,6 +916,84 @@ describe('Dependency checks (eslint)', () => { `); }); + it('should remove obsolete package at the end with fix', () => { + const packageJson = { + name: '@mycompany/liba', + peerDependencies: { + external1: '^16.0.0', + external2: '^5.2.0', + unneeded: '>= 16 < 18', + }, + }; + + const fileSys = { + './libs/liba/package.json': JSON.stringify(packageJson, null, 2), + './libs/liba/src/index.ts': '', + './package.json': JSON.stringify(rootPackageJson, null, 2), + }; + vol.fromJSON(fileSys, '/root'); + + const failures = runRule( + {}, + `${process.cwd()}/proj/libs/liba/package.json`, + JSON.stringify(packageJson, null, 2), + { + nodes: { + liba: { + name: 'liba', + type: 'lib', + data: { + root: 'libs/liba', + targets: { + build: {}, + }, + }, + }, + }, + externalNodes, + dependencies: { + liba: [ + { source: 'liba', target: 'npm:external1', type: 'static' }, + { source: 'liba', target: 'npm:external2', type: 'static' }, + ], + }, + }, + { + liba: [ + createFile(`libs/liba/src/main.ts`, [ + 'npm:external1', + 'npm:external2', + ]), + createFile(`libs/liba/package.json`, [ + 'npm:external1', + 'npm:external2', + 'npm:unneeded', + ]), + ], + } + ); + expect(failures.length).toEqual(1); + expect(failures[0].message).toMatchInlineSnapshot( + `"The "unneeded" package is not used by "liba"."` + ); + + // should apply fixer + const content = JSON.stringify(packageJson, null, 2); + const result = + content.slice(0, failures[0].fix.range[0]) + + failures[0].fix.text + + content.slice(failures[0].fix.range[1]); + expect(result).toMatchInlineSnapshot(` + "{ + "name": "@mycompany/liba", + "peerDependencies": { + "external1": "^16.0.0", + "external2": "^5.2.0" + } + }" + `); + }); + it('should not check obsolete deps if checkObsoleteDependencies=false', () => { const packageJson = { name: '@mycompany/liba', diff --git a/packages/eslint-plugin/src/rules/dependency-checks.ts b/packages/eslint-plugin/src/rules/dependency-checks.ts index 84d6f38d55350..19b6916b122ba 100644 --- a/packages/eslint-plugin/src/rules/dependency-checks.ts +++ b/packages/eslint-plugin/src/rules/dependency-checks.ts @@ -242,7 +242,7 @@ export default createESLintRule({ if (index > 0) { const previousNode = node.parent.properties[index - 1]; return fixer.removeRange([ - previousNode.range[1] + 1, + previousNode.range[1] + (isLastProperty ? 0 : 1), node.range[1] + (isLastProperty ? 0 : 1), ]); } else {