Skip to content

feat: add no-container rule #177

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

Merged
merged 21 commits into from
Jun 21, 2020
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
[![Tweet][tweet-badge]][tweet-url]

<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-26-orange.svg?style=flat-square)](#contributors-)

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

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

## Installation
Expand Down Expand Up @@ -138,14 +140,15 @@ To enable this configuration use the `extends` property in your
| [await-fire-event](docs/rules/await-fire-event.md) | Enforce async fire event methods to be awaited | ![vue-badge][] | |
| [consistent-data-testid](docs/rules/consistent-data-testid.md) | Ensure `data-testid` values match a provided regex. | | |
| [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-container](docs/rules/no-container.md) | Disallow the use of `container` methods | ![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][] | |
| [no-dom-import](docs/rules/no-dom-import.md) | Disallow importing from DOM Testing Library | ![angular-badge][] ![react-badge][] ![vue-badge][] | ![fixable-badge][] |
| [no-manual-cleanup](docs/rules/no-manual-cleanup.md) | Disallow the use of `cleanup` | | |
| [no-wait-for-empty-callback](docs/rules/no-wait-for-empty-callback.md) | Disallow empty callbacks for `waitFor` and `waitForElementToBeRemoved` | | |
| [no-wait-for-empty-callback](docs/rules/no-wait-for-empty-callback.md) | Disallow empty callbacks for `waitFor` and `waitForElementToBeRemoved` | ![recommended-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [prefer-explicit-assert](docs/rules/prefer-explicit-assert.md) | Suggest using explicit assertions rather than just `getBy*` queries | | |
| [prefer-find-by](docs/rules/prefer-find-by.md) | Suggest using `findBy*` methods instead of the `waitFor` + `getBy` queries | ![recommended-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | ![fixable-badge][] |
| [prefer-presence-queries](docs/rules/prefer-presence-queries.md) | Enforce specific queries when checking element is present or not | | |
| [prefer-screen-queries](docs/rules/prefer-screen-queries.md) | Suggest using screen while using queries | | |
| [prefer-screen-queries](docs/rules/prefer-screen-queries.md) | Suggest using screen while using queries | ![recommended-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [prefer-wait-for](docs/rules/prefer-wait-for.md) | Use `waitFor` instead of deprecated wait methods | | ![fixable-badge][] |

[build-badge]: https://img.shields.io/travis/testing-library/eslint-plugin-testing-library?style=flat-square
Expand Down Expand Up @@ -214,6 +217,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d

<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->

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

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
36 changes: 36 additions & 0 deletions docs/rules/no-container.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Disallow the use of `container` methods (no-container)

By using `container` methods like `.querySelector` you may lose a lot of the confidence that the user can really interact with your UI. Also, the test becomes harder to read, and it will break more frequently.

## Rule Details

This rule aims to disallow the use of `container` methods in your tests.

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

```js
const { container } = render(<Example />);
const button = container.querySelector('.btn-primary');
```

```js
const { container: alias } = render(<Example />);
const button = alias.querySelector('.btn-primary');
```

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

```js
render(<Example />);
screen.getByRole('button', { name: /click me/i });
```

If you use [custom render functions](https://testing-library.com/docs/example-react-redux) then you can set a config option in your `.eslintrc` to look for these.

```
"testing-library/no-container": ["error", {"renderFunctions":["renderWithRedux", "renderWithRouter"]}],
```

## Further Reading

- [querying with `screen`](https://testing-library.com/docs/dom-testing-library/api-queries#screen)
5 changes: 5 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import awaitAsyncUtils from './rules/await-async-utils';
import awaitFireEvent from './rules/await-fire-event';
import consistentDataTestid from './rules/consistent-data-testid';
import noAwaitSyncQuery from './rules/no-await-sync-query';
import noContainer from './rules/no-container';
import noDebug from './rules/no-debug';
import noDomImport from './rules/no-dom-import';
import noManualCleanup from './rules/no-manual-cleanup';
Expand All @@ -19,6 +20,7 @@ const rules = {
'await-fire-event': awaitFireEvent,
'consistent-data-testid': consistentDataTestid,
'no-await-sync-query': noAwaitSyncQuery,
'no-container': noContainer,
'no-debug': noDebug,
'no-dom-import': noDomImport,
'no-manual-cleanup': noManualCleanup,
Expand All @@ -34,7 +36,10 @@ const recommendedRules = {
'testing-library/await-async-query': 'error',
'testing-library/await-async-utils': 'error',
'testing-library/no-await-sync-query': 'error',
'testing-library/no-container': 'error',
'testing-library/no-wait-for-empty-callback': 'error',
'testing-library/prefer-find-by': 'error',
'testing-library/prefer-screen-queries': 'error',
};

export = {
Expand Down
33 changes: 33 additions & 0 deletions lib/node-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,37 @@ export function hasThenProperty(node: TSESTree.Node) {

export function isArrowFunctionExpression(node: TSESTree.Node): node is TSESTree.ArrowFunctionExpression {
return node && node.type === 'ArrowFunctionExpression'
}

function isRenderFunction(
callNode: TSESTree.CallExpression,
renderFunctions: string[]
) {
return ['render', ...renderFunctions].some(
name => isIdentifier(callNode.callee) && name === callNode.callee.name
);
}

export function isRenderVariableDeclarator(
node: TSESTree.VariableDeclarator,
renderFunctions: string[]
) {
if (node.init) {
if (isAwaitExpression(node.init)) {
return (
node.init.argument &&
isRenderFunction(
node.init.argument as TSESTree.CallExpression,
renderFunctions
)
);
} else {
return (
isCallExpression(node.init) &&
isRenderFunction(node.init, renderFunctions)
);
}
}

return false;
}
82 changes: 82 additions & 0 deletions lib/rules/no-container.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import { getDocsUrl } from '../utils';
import {
isCallExpression,
isIdentifier,
isMemberExpression,
isObjectPattern,
isProperty,
isRenderVariableDeclarator,
} from '../node-utils';

export const RULE_NAME = 'no-container';

export default ESLintUtils.RuleCreator(getDocsUrl)({
name: RULE_NAME,
meta: {
type: 'problem',
docs: {
description: 'Disallow the use of container methods',
category: 'Best Practices',
recommended: 'error',
},
messages: {
noContainer:
'Unexpected use of container methods. Prefer the use of "screen.someMethod()".',
},
fixable: null,
schema: [
{
type: 'object',
properties: {
renderFunctions: {
type: 'array',
},
},
},
],
},
defaultOptions: [
{
renderFunctions: [],
},
],

create(context, [options]) {
const { renderFunctions } = options;
let destructuredContainerName = '';

return {
VariableDeclarator(node) {
if (isRenderVariableDeclarator(node, renderFunctions)) {
if (isObjectPattern(node.id)) {
const containerIndex = node.id.properties.findIndex(
property =>
isProperty(property) &&
isIdentifier(property.key) &&
property.key.name === 'container'
);
if (containerIndex !== -1) {
const nodeValue = node.id.properties[containerIndex].value;
destructuredContainerName =
isIdentifier(nodeValue) && nodeValue.name;
}
}
}
},

CallExpression(node: TSESTree.CallExpression) {
if (
isMemberExpression(node.callee) &&
isIdentifier(node.callee.object) &&
node.callee.object.name === destructuredContainerName
) {
context.report({
node,
messageId: 'noContainer',
});
}
},
};
},
});
35 changes: 1 addition & 34 deletions lib/rules/no-debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,46 +6,13 @@ import {
isIdentifier,
isCallExpression,
isLiteral,
isAwaitExpression,
isMemberExpression,
isImportSpecifier,
isRenderVariableDeclarator,
} from '../node-utils';

export const RULE_NAME = 'no-debug';

function isRenderFunction(
callNode: TSESTree.CallExpression,
renderFunctions: string[]
) {
return ['render', ...renderFunctions].some(
name => isIdentifier(callNode.callee) && name === callNode.callee.name
);
}

function isRenderVariableDeclarator(
node: TSESTree.VariableDeclarator,
renderFunctions: string[]
) {
if (node.init) {
if (isAwaitExpression(node.init)) {
return (
node.init.argument &&
isRenderFunction(
node.init.argument as TSESTree.CallExpression,
renderFunctions
)
);
} else {
return (
isCallExpression(node.init) &&
isRenderFunction(node.init, renderFunctions)
);
}
}

return false;
}

function hasTestingLibraryImportModule(
importDeclarationNode: TSESTree.ImportDeclaration
) {
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/no-wait-for-empty-callback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
description:
"It's preferred to avoid empty callbacks in `waitFor` and `waitForElementToBeRemoved`",
category: 'Best Practices',
recommended: false,
recommended: 'error',
},
messages: {
noWaitForEmptyCallback:
Expand Down
32 changes: 21 additions & 11 deletions lib/rules/prefer-screen-queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
docs: {
description: 'Suggest using screen while using queries',
category: 'Best Practices',
recommended: false,
recommended: 'error',
},
messages: {
preferScreenQueries:
Expand All @@ -46,28 +46,39 @@ export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
const queriesRegex = new RegExp(ALL_QUERIES_COMBINATIONS_REGEXP);
const queriesDestructuredInWithinDeclaration: string[] = [];
// use an array as within might be used more than once in a test
const withinDeclaredVariables : string[] = []
const withinDeclaredVariables: string[] = [];

return {
VariableDeclarator(node) {
const isWithinFunction = isCallExpression(node.init) && isIdentifier(node.init.callee) && node.init.callee.name === 'within';
const isWithinFunction =
isCallExpression(node.init) &&
isIdentifier(node.init.callee) &&
node.init.callee.name === 'within';

if (!isWithinFunction) {
return
return;
}

if (isObjectPattern(node.id)) {
// save the destructured query methods
const identifiers = node.id.properties
.filter(property => isProperty(property) && isIdentifier(property.key) && queriesRegex.test(property.key.name))
.map((property: TSESTree.Property) => (property.key as TSESTree.Identifier).name);
.filter(
property =>
isProperty(property) &&
isIdentifier(property.key) &&
queriesRegex.test(property.key.name)
)
.map(
(property: TSESTree.Property) =>
(property.key as TSESTree.Identifier).name
);

queriesDestructuredInWithinDeclaration.push(...identifiers);
return
return;
}

if (isIdentifier(node.id)) {
withinDeclaredVariables.push(node.id.name)
withinDeclaredVariables.push(node.id.name);
}
},
[`CallExpression > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`](
Expand All @@ -84,16 +95,15 @@ export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
[`MemberExpression > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`](
node: TSESTree.Identifier
) {

function isIdentifierAllowed(name: string) {
return ['screen', ...withinDeclaredVariables].includes(name)
return ['screen', ...withinDeclaredVariables].includes(name);
}

if (
isIdentifier(node) &&
isMemberExpression(node.parent) &&
isCallExpression(node.parent.object) &&
isIdentifier(node.parent.object.callee) &&
isIdentifier(node.parent.object.callee) &&
node.parent.object.callee.name !== 'within'
) {
reportInvalidUsage(node);
Expand Down
Loading