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

feat: new rule await-async-utils #69

Merged
merged 6 commits into from
Jan 28, 2020
Merged
Show file tree
Hide file tree
Changes from 5 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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->

[![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors)
[![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors-)
Copy link
Member Author

Choose a reason for hiding this comment

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

I removed this by mistake in that PR trying to fix the badges.


<!-- ALL-CONTRIBUTORS-BADGE:END -->

Expand Down Expand Up @@ -137,6 +137,7 @@ To enable this configuration use the `extends` property in your
| Rule | Description | Configurations | Fixable |
| -------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------ |
| [await-async-query](docs/rules/await-async-query.md) | Enforce async queries to have proper `await` | ![recommended-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [await-async-utils](docs/rules/await-async-utils.md) | Enforce async utils to be awaited properly | ![recommended-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [await-fire-event](docs/rules/await-fire-event.md) | Enforce async fire event methods to be awaited | ![vue-badge][] | |
| [no-await-sync-query](docs/rules/no-await-sync-query.md) | Disallow unnecessary `await` for sync queries | ![recommended-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [no-debug](docs/rules/no-debug.md) | Disallow the use of `debug` | ![angular-badge][] ![react-badge][] ![vue-badge][] | |
Expand Down
72 changes: 72 additions & 0 deletions docs/rules/await-async-utils.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Enforce async utils to be awaited properly (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:

- `wait`
- `waitForElement`
- `waitForDomChange`
- `waitForElementToBeRemoved`

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.

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

```js
test('something incorrectly', async () => {
// ...
wait(() => getByLabelText('email'));

const [usernameElement, passwordElement] = waitForElement(
() => [
getByLabelText(container, 'username'),
getByLabelText(container, 'password'),
],
{ container }
);

waitForDomChange(() => {
return { container };
});

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

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

```js
test('something correctly', async () => {
// ...
// `await` operator is correct
await wait(() => getByLabelText('email'));

const [usernameElement, passwordElement] = await waitForElement(
() => [
getByLabelText(container, 'username'),
getByLabelText(container, 'password'),
],
{ container }
);

// `then` chained method is correct
waitForDomChange(() => {
return { container };
})
.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'));
// ...
});
```

## Further Reading

- [Async Utilities](https://testing-library.com/docs/dom-testing-library/api-async)
2 changes: 2 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const rules = {
'await-async-query': require('./rules/await-async-query'),
'await-async-utils': require('./rules/await-async-utils'),
'await-fire-event': require('./rules/await-fire-event'),
'consistent-data-testid': require('./rules/consistent-data-testid'),
'no-await-sync-query': require('./rules/no-await-sync-query'),
Expand All @@ -13,6 +14,7 @@ const rules = {

const recommendedRules = {
'testing-library/await-async-query': 'error',
'testing-library/await-async-utils': 'error',
'testing-library/no-await-sync-query': 'error',
};

Expand Down
103 changes: 103 additions & 0 deletions lib/rules/await-async-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
'use strict';
Copy link
Member Author

Choose a reason for hiding this comment

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

This rule implementation is almost the same as await-async-query but I didn't try to optimize this as we may migrate this to TS soon.


const { getDocsUrl, ASYNC_UTILS } = require('../utils');

const VALID_PARENTS = [
'AwaitExpression',
'ArrowFunctionExpression',
'ReturnStatement',
];

const ASYNC_UTILS_REGEXP = new RegExp(`^(${ASYNC_UTILS.join('|')})$`);

module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Enforce async utils to be awaited properly',
category: 'Best Practices',
recommended: true,
url: getDocsUrl('await-async-utils'),
},
messages: {
awaitAsyncUtil: 'Promise returned from `{{ name }}` must be handled',
},
fixable: null,
schema: [],
},

create: function(context) {
const testingLibraryUtilUsage = [];
return {
[`CallExpression > Identifier[name=${ASYNC_UTILS_REGEXP}]`](node) {
if (!isAwaited(node.parent.parent) && !isPromiseResolved(node)) {
testingLibraryUtilUsage.push(node);
}
},
'Program:exit'() {
Copy link
Contributor

Choose a reason for hiding this comment

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

Ah interesting, I didn’t know about this

Copy link
Member Author

Choose a reason for hiding this comment

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

Me either! I learnt about it thanks to @thomlom, you can find more info here

testingLibraryUtilUsage.forEach(node => {
const variableDeclaratorParent = node.parent.parent;

const references =
(variableDeclaratorParent.type === 'VariableDeclarator' &&
context
.getDeclaredVariables(variableDeclaratorParent)[0]
.references.slice(1)) ||
[];

if (
references &&
references.length === 0 &&
!isAwaited(node.parent.parent) &&
!isPromiseResolved(node)
) {
context.report({
node,
messageId: 'awaitAsyncUtil',
data: {
name: node.name,
},
});
} else {
for (const reference of references) {
const referenceNode = reference.identifier;
if (
!isAwaited(referenceNode.parent) &&
!isPromiseResolved(referenceNode)
) {
context.report({
node,
messageId: 'awaitAsyncUtil',
data: {
name: node.name,
},
});

break;
}
}
}
});
},
};
},
};

function isAwaited(node) {
return VALID_PARENTS.includes(node.type);
}

function isPromiseResolved(node) {
const parent = node.parent;

const hasAThenProperty = node =>
Copy link
Contributor

Choose a reason for hiding this comment

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

Does this need to be declared inside the isPromiseResolved function? Just to avoid confusion with arg names.

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, let me move this outside.

node.type === 'MemberExpression' && node.property.name === 'then';

// wait(...).then(...)
if (parent.type === 'CallExpression') {
return hasAThenProperty(parent.parent);
}

// promise.then(...)
return hasAThenProperty(parent);
}
8 changes: 8 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ const ALL_QUERIES_COMBINATIONS = [
ASYNC_QUERIES_COMBINATIONS,
];

const ASYNC_UTILS = [
'wait',
'waitForElement',
'waitForDomChange',
'waitForElementToBeRemoved',
];

module.exports = {
getDocsUrl,
SYNC_QUERIES_VARIANTS,
Expand All @@ -57,4 +64,5 @@ module.exports = {
SYNC_QUERIES_COMBINATIONS,
ASYNC_QUERIES_COMBINATIONS,
ALL_QUERIES_COMBINATIONS,
ASYNC_UTILS,
};
4 changes: 4 additions & 0 deletions tests/__snapshots__/index.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Object {
],
"rules": Object {
"testing-library/await-async-query": "error",
"testing-library/await-async-utils": "error",
"testing-library/no-await-sync-query": "error",
"testing-library/no-debug": "warn",
"testing-library/no-dom-import": Array [
Expand All @@ -24,6 +25,7 @@ Object {
],
"rules": Object {
"testing-library/await-async-query": "error",
"testing-library/await-async-utils": "error",
"testing-library/no-await-sync-query": "error",
"testing-library/no-debug": "warn",
"testing-library/no-dom-import": Array [
Expand All @@ -41,6 +43,7 @@ Object {
],
"rules": Object {
"testing-library/await-async-query": "error",
"testing-library/await-async-utils": "error",
"testing-library/no-await-sync-query": "error",
},
}
Expand All @@ -53,6 +56,7 @@ Object {
],
"rules": Object {
"testing-library/await-async-query": "error",
"testing-library/await-async-utils": "error",
"testing-library/await-fire-event": "error",
"testing-library/no-await-sync-query": "error",
"testing-library/no-debug": "warn",
Expand Down
Loading