From 9a2560b598ced62abffcaeb0de5a74fbfe8db32c Mon Sep 17 00:00:00 2001 From: Gareth Jones Date: Fri, 16 Jul 2021 09:31:01 +1200 Subject: [PATCH] feat(prefer-expect-resolves): add fixer --- .../__tests__/prefer-expect-resolves.test.ts | 12 ++++++++++++ src/rules/prefer-expect-resolves.ts | 16 ++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/rules/__tests__/prefer-expect-resolves.test.ts b/src/rules/__tests__/prefer-expect-resolves.test.ts index c76e99f53..0eeb1be84 100644 --- a/src/rules/__tests__/prefer-expect-resolves.test.ts +++ b/src/rules/__tests__/prefer-expect-resolves.test.ts @@ -37,6 +37,11 @@ ruleTester.run('prefer-expect-resolves', rule, { expect(await someValue()).toBe(true); }); `, + output: dedent` + it('passes', async () => { + await expect(someValue()).resolves.toBe(true); + }); + `, errors: [{ endColumn: 27, column: 10, messageId: 'expectResolves' }], }, { @@ -47,6 +52,13 @@ ruleTester.run('prefer-expect-resolves', rule, { expect(await myPromise).toBe(true); }); `, + output: dedent` + it('is true', async () => { + const myPromise = Promise.resolve(true); + + await expect(myPromise).resolves.toBe(true); + }); + `, errors: [{ endColumn: 25, column: 10, messageId: 'expectResolves' }], }, ], diff --git a/src/rules/prefer-expect-resolves.ts b/src/rules/prefer-expect-resolves.ts index d4802fb62..dd644d11d 100644 --- a/src/rules/prefer-expect-resolves.ts +++ b/src/rules/prefer-expect-resolves.ts @@ -13,6 +13,7 @@ export default createRule({ 'Prefer `await expect(...).resolves` over `expect(await ...)` syntax', recommended: false, }, + fixable: 'code', messages: { expectResolves: 'Use `await expect(...).resolves instead.', }, @@ -22,14 +23,25 @@ export default createRule({ defaultOptions: [], create: context => ({ CallExpression(node: TSESTree.CallExpression) { + const [awaitNode] = node.arguments; + if ( isExpectCall(node) && - node.arguments.length && - node.arguments[0].type === AST_NODE_TYPES.AwaitExpression + awaitNode?.type === AST_NODE_TYPES.AwaitExpression ) { context.report({ node: node.arguments[0], messageId: 'expectResolves', + fix(fixer) { + return [ + fixer.insertTextBefore(node, 'await '), + fixer.removeRange([ + awaitNode.range[0], + awaitNode.argument.range[0], + ]), + fixer.insertTextAfter(node, '.resolves'), + ]; + }, }); } },