Skip to content
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

Move rules settings to ESLint shared config: refactor await-async-utils #263

Merged
merged 15 commits into from
Dec 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really sure how to call this one. Suggestions?

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
Loading