Skip to content

Commit

Permalink
feat(prefer-expect-resolves): add fixer
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath committed Jul 15, 2021
1 parent 543ce3f commit 9a2560b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
12 changes: 12 additions & 0 deletions src/rules/__tests__/prefer-expect-resolves.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' }],
},
{
Expand All @@ -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' }],
},
],
Expand Down
16 changes: 14 additions & 2 deletions src/rules/prefer-expect-resolves.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
},
Expand All @@ -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'),
];
},
});
}
},
Expand Down

0 comments on commit 9a2560b

Please sign in to comment.