-
Notifications
You must be signed in to change notification settings - Fork 150
feat: new rule await-async-utils #69
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
Changes from 3 commits
34dfde6
5caa05c
0b2c917
3784fa6
6177975
9f1005a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
'use strict'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This rule implementation is almost the same as |
||
|
||
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'() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah interesting, I didn’t know about this There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 => | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this need to be declared inside the There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
'use strict'; | ||
|
||
const rule = require('../../../lib/rules/await-async-utils'); | ||
const { ASYNC_UTILS } = require('../../../lib/utils'); | ||
const RuleTester = require('eslint').RuleTester; | ||
|
||
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2018 } }); | ||
|
||
ruleTester.run('await-async-utils', rule, { | ||
valid: [ | ||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util directly waited with await operator is valid', async () => { | ||
doSomethingElse(); | ||
await ${asyncUtil}(() => getByLabelText('email')); | ||
}); | ||
`, | ||
})), | ||
|
||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util promise saved in var and waited with await operator is valid', async () => { | ||
doSomethingElse(); | ||
const aPromise = ${asyncUtil}(() => getByLabelText('email')); | ||
await aPromise; | ||
}); | ||
`, | ||
})), | ||
|
||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util directly chained with then is valid', () => { | ||
doSomethingElse(); | ||
${asyncUtil}(() => getByLabelText('email')).then(() => { console.log('done') }); | ||
}); | ||
`, | ||
})), | ||
|
||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util promise saved in var and chained with then is valid', () => { | ||
doSomethingElse(); | ||
const aPromise = ${asyncUtil}(() => getByLabelText('email')); | ||
aPromise.then(() => { console.log('done') }); | ||
}); | ||
`, | ||
})), | ||
|
||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util directly returned in arrow function is valid', async () => { | ||
const makeCustomWait = () => | ||
${asyncUtil}(() => | ||
document.querySelector('div.getOuttaHere') | ||
); | ||
}); | ||
`, | ||
})), | ||
|
||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util explicitly returned in arrow function is valid', async () => { | ||
const makeCustomWait = () => { | ||
return ${asyncUtil}(() => | ||
document.querySelector('div.getOuttaHere') | ||
); | ||
}; | ||
}); | ||
`, | ||
})), | ||
|
||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util returned in regular function is valid', async () => { | ||
function makeCustomWait() { | ||
return ${asyncUtil}(() => | ||
document.querySelector('div.getOuttaHere') | ||
); | ||
} | ||
}); | ||
`, | ||
})), | ||
|
||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util promise saved in var and returned in function is valid', async () => { | ||
const makeCustomWait = () => { | ||
const aPromise = ${asyncUtil}(() => | ||
document.querySelector('div.getOuttaHere') | ||
); | ||
|
||
doSomethingElse(); | ||
|
||
return aPromise; | ||
}; | ||
}); | ||
`, | ||
})), | ||
], | ||
invalid: [ | ||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util not waited', () => { | ||
doSomethingElse(); | ||
${asyncUtil}(() => getByLabelText('email')); | ||
}); | ||
`, | ||
errors: [{ line: 4, messageId: 'awaitAsyncUtil' }], | ||
})), | ||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('${asyncUtil} util promise saved not waited', () => { | ||
doSomethingElse(); | ||
const aPromise = ${asyncUtil}(() => getByLabelText('email')); | ||
}); | ||
`, | ||
errors: [{ line: 4, column: 28, messageId: 'awaitAsyncUtil' }], | ||
})), | ||
...ASYNC_UTILS.map(asyncUtil => ({ | ||
code: ` | ||
test('several ${asyncUtil} utils not waited', () => { | ||
${asyncUtil}(() => getByLabelText('username')); | ||
doSomethingElse(); | ||
${asyncUtil}(() => getByLabelText('email')); | ||
}); | ||
`, | ||
errors: [ | ||
{ line: 3, messageId: 'awaitAsyncUtil' }, | ||
{ line: 5, messageId: 'awaitAsyncUtil' }, | ||
], | ||
})), | ||
], | ||
}); |
There was a problem hiding this comment.
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.