Skip to content

Commit

Permalink
refactor(await-async-utils): use custom rule creator (#263)
Browse files Browse the repository at this point in the history
* refactor: extract utils for checking promise all methods

* test(await-async-query): add cases for promise all and allSettled

* docs(await-async-query): add cases for promise all and allSettled

* refactor(await-async-utils): create rule with custom creator

* refactor(await-async-utils): replace async utils regexp by method

* refactor(await-async-utils): replace manual import checks by helper

* refactor(await-async-utils): replace manual promise checks by util

* refactor(await-async-utils): merge identifier and member expression nodes checks

* test(await-async-query): check column on invalid cases

* test(await-async-query): promise.allSettled cases

* refactor(await-async-query): extract util to get innermost returning function name

* feat(await-async-utils): report unhandled functions wrapping async utils

* docs: minor improvements

* test(await-async-utils): increase coverage

* refactor: repurpose getInnermostReturningFunctionName to getInnermostReturningFunction
  • Loading branch information
Belco90 committed Dec 6, 2020
1 parent dcc0693 commit 9062040
Show file tree
Hide file tree
Showing 8 changed files with 325 additions and 162 deletions.
18 changes: 16 additions & 2 deletions docs/rules/await-async-query.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ found. Those queries variants are:
- `findAllBy*`

This rule aims to prevent users from forgetting to handle the returned
promise from those async queries to be fulfilled, which could lead to
errors in the tests. The promise will be considered as handled when:
promise from those async queries, which could lead to
problems in the tests. The promise will be considered as handled when:

- using the `await` operator
- wrapped within `Promise.all` or `Promise.allSettled` methods
- chaining the `then` method
- chaining `resolves` or `rejects` from jest
- it's returned from a function (in this case, that particular function will be analyzed by this rule too)
Expand Down Expand Up @@ -70,6 +71,19 @@ const findMyButton = () => findByText('my button');
const someButton = await findMyButton();
```

```js
// several promises handled with `Promise.all` is correct
await Promise.all([findByText('my button'), findByText('something else')]);
```

```js
// several promises handled `Promise.allSettled` is correct
await Promise.allSettled([
findByText('my button'),
findByText('something else'),
]);
```

```js
// using a resolves/rejects matcher is also correct
expect(findByTestId('alert')).resolves.toBe('Success');
Expand Down
38 changes: 29 additions & 9 deletions docs/rules/await-async-utils.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
# Enforce async utils to be awaited properly (await-async-utils)
# Enforce promises from async utils to be handled (await-async-utils)

Ensure that promises returned by async utils are handled properly.

## Rule Details

Testing library provides several utilities for dealing with asynchronous code. These are useful to wait for an element until certain criteria or situation happens. The available async utils are:

- `waitFor` _(introduced in dom-testing-library v7)_
- `waitFor` _(introduced since dom-testing-library v7)_
- `waitForElementToBeRemoved`
- `wait` _(**deprecated** in dom-testing-library v7)_
- `waitForElement` _(**deprecated** in dom-testing-library v7)_
- `waitForDomChange` _(**deprecated** in dom-testing-library v7)_
- `wait` _(**deprecated** since dom-testing-library v7)_
- `waitForElement` _(**deprecated** since dom-testing-library v7)_
- `waitForDomChange` _(**deprecated** since dom-testing-library v7)_

This rule aims to prevent users from forgetting to handle the returned promise from those async utils, which could lead to unexpected errors in the tests execution. The promises can be handled by using either `await` operator or `then` method.
This rule aims to prevent users from forgetting to handle the returned
promise from async utils, which could lead to
problems in the tests. The promise will be considered as handled when:

- using the `await` operator
- wrapped within `Promise.all` or `Promise.allSettled` methods
- chaining the `then` method
- chaining `resolves` or `rejects` from jest
- it's returned from a function (in this case, that particular function will be analyzed by this rule too)

Examples of **incorrect** code for this rule:

Expand All @@ -32,6 +40,14 @@ test('something incorrectly', async () => {
waitFor(() => {}, { timeout: 100 });

waitForElementToBeRemoved(() => document.querySelector('div.getOuttaHere'));

// wrap an async util within a function...
const makeCustomWait = () => {
return waitForElementToBeRemoved(() =>
document.querySelector('div.getOuttaHere')
);
};
makeCustomWait(); // ...but not handling promise from it is incorrect
});
```

Expand All @@ -56,9 +72,13 @@ test('something correctly', async () => {
.then(() => console.log('DOM changed!'))
.catch((err) => console.log(`Error you need to deal with: ${err}`));

// return the promise within a function is correct too!
const makeCustomWait = () =>
waitForElementToBeRemoved(() => document.querySelector('div.getOuttaHere'));
// wrap an async util within a function...
const makeCustomWait = () => {
return waitForElementToBeRemoved(() =>
document.querySelector('div.getOuttaHere')
);
};
await makeCustomWait(); // ...and handling promise from it is correct

// using Promise.all combining the methods
await Promise.all([
Expand Down
11 changes: 10 additions & 1 deletion lib/detect-testing-library-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
isCallExpression,
isObjectPattern,
} from './node-utils';
import { ABSENCE_MATCHERS, PRESENCE_MATCHERS } from './utils';
import { ABSENCE_MATCHERS, ASYNC_UTILS, PRESENCE_MATCHERS } from './utils';

export type TestingLibrarySettings = {
'testing-library/module'?: string;
Expand Down Expand Up @@ -53,6 +53,7 @@ export type DetectionHelpers = {
isFindByQuery: (node: TSESTree.Identifier) => boolean;
isSyncQuery: (node: TSESTree.Identifier) => boolean;
isAsyncQuery: (node: TSESTree.Identifier) => boolean;
isAsyncUtil: (node: TSESTree.Identifier) => boolean;
isPresenceAssert: (node: TSESTree.MemberExpression) => boolean;
isAbsenceAssert: (node: TSESTree.MemberExpression) => boolean;
canReportErrors: () => boolean;
Expand Down Expand Up @@ -168,6 +169,13 @@ export function detectTestingLibraryUtils<
return isFindByQuery(node);
};

/**
* Determines whether a given node is async util or not.
*/
const isAsyncUtil: DetectionHelpers['isAsyncUtil'] = (node) => {
return ASYNC_UTILS.includes(node.name);
};

/**
* Determines whether a given MemberExpression node is a presence assert
*
Expand Down Expand Up @@ -312,6 +320,7 @@ export function detectTestingLibraryUtils<
isFindByQuery,
isSyncQuery,
isAsyncQuery,
isAsyncUtil,
isPresenceAssert,
isAbsenceAssert,
canReportErrors,
Expand Down
72 changes: 72 additions & 0 deletions lib/node-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,45 @@ export function hasChainedThen(node: TSESTree.Node): boolean {
return hasThenProperty(parent);
}

export function isPromiseAll(node: TSESTree.CallExpression): boolean {
return (
isMemberExpression(node.callee) &&
ASTUtils.isIdentifier(node.callee.object) &&
node.callee.object.name === 'Promise' &&
ASTUtils.isIdentifier(node.callee.property) &&
node.callee.property.name === 'all'
);
}

export function isPromiseAllSettled(node: TSESTree.CallExpression): boolean {
return (
isMemberExpression(node.callee) &&
ASTUtils.isIdentifier(node.callee.object) &&
node.callee.object.name === 'Promise' &&
ASTUtils.isIdentifier(node.callee.property) &&
node.callee.property.name === 'allSettled'
);
}

export function isPromisesArrayResolved(node: TSESTree.Node): boolean {
const parent = node.parent;

return (
isCallExpression(parent) &&
isArrayExpression(parent.parent) &&
isCallExpression(parent.parent.parent) &&
(isPromiseAll(parent.parent.parent) ||
isPromiseAllSettled(parent.parent.parent))
);
}

/**
* Determines whether an Identifier related to a promise is considered as handled.
*
* It will be considered as handled if:
* - it belongs to the `await` expression
* - it belongs to the `Promise.all` method
* - it belongs to the `Promise.allSettled` method
* - it's chained with the `then` method
* - it's returned from a function
* - has `resolves` or `rejects`
Expand Down Expand Up @@ -250,6 +284,10 @@ export function isPromiseHandled(nodeIdentifier: TSESTree.Identifier): boolean {
if (hasChainedThen(node)) {
return true;
}

if (isPromisesArrayResolved(node)) {
return true;
}
}

return false;
Expand Down Expand Up @@ -476,3 +514,37 @@ export function hasClosestExpectResolvesRejects(node: TSESTree.Node): boolean {

return hasClosestExpectResolvesRejects(node.parent);
}

/**
* Gets the Function node which returns the given Identifier.
*/
export function getInnermostReturningFunction(
context: RuleContext<string, []>,
node: TSESTree.Identifier
):
| TSESTree.FunctionDeclaration
| TSESTree.FunctionExpression
| TSESTree.ArrowFunctionExpression
| undefined {
const functionScope = getInnermostFunctionScope(context, node);

if (!functionScope) {
return;
}

const returnStatementNode = getFunctionReturnStatementNode(
functionScope.block
);

if (!returnStatementNode) {
return;
}

const returnStatementIdentifier = getIdentifierNode(returnStatementNode);

if (returnStatementIdentifier?.name !== node.name) {
return;
}

return functionScope.block;
}
26 changes: 4 additions & 22 deletions lib/rules/await-async-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { ASTUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import {
findClosestCallExpressionNode,
getFunctionName,
getFunctionReturnStatementNode,
getIdentifierNode,
getInnermostFunctionScope,
getInnermostReturningFunction,
getVariableReferences,
isPromiseHandled,
} from '../node-utils';
Expand Down Expand Up @@ -37,25 +35,9 @@ export default createTestingLibraryRule<Options, MessageIds>({
const functionWrappersNames: string[] = [];

function detectAsyncQueryWrapper(node: TSESTree.Identifier) {
const functionScope = getInnermostFunctionScope(context, node);

if (functionScope) {
// save function wrapper calls rather than async calls to be reported later
const returnStatementNode = getFunctionReturnStatementNode(
functionScope.block
);

if (!returnStatementNode) {
return;
}

const returnStatementIdentifier = getIdentifierNode(
returnStatementNode
);

if (returnStatementIdentifier?.name === node.name) {
functionWrappersNames.push(getFunctionName(functionScope.block));
}
const innerFunction = getInnermostReturningFunction(context, node);
if (innerFunction) {
functionWrappersNames.push(getFunctionName(innerFunction));
}
}

Expand Down

0 comments on commit 9062040

Please sign in to comment.