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: add render-result-naming-convention rule #200

Merged
merged 18 commits into from
Jul 27, 2020
Merged
Show file tree
Hide file tree
Changes from 11 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
41 changes: 21 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,27 +125,28 @@ To enable this configuration use the `extends` property in your

## Supported Rules

| Rule | Description | Configurations | Fixable |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------ |
| [await-async-query](docs/rules/await-async-query.md) | Enforce async queries to have proper `await` | ![dom-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [await-async-utils](docs/rules/await-async-utils.md) | Enforce async utils to be awaited properly | ![dom-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][] | |
| [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 | ![dom-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [no-container](docs/rules/no-container.md) | Disallow the use of `container` methods | ![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-multiple-assertions-wait-for](docs/rules/no-multiple-assertions-wait-for.md) | Disallow the use of multiple expect inside `waitFor` | | |
| [no-node-access](docs/rules/no-node-access.md) | Disallow direct Node access | ![angular-badge][] ![react-badge][] ![vue-badge][] | | |
| [no-promise-in-fire-event](docs/rules/no-promise-in-fire-event.md) | Disallow the use of promises passed to a `fireEvent` method | | |
| [no-wait-for-empty-callback](docs/rules/no-wait-for-empty-callback.md) | Disallow empty callbacks for `waitFor` and `waitForElementToBeRemoved` | ![dom-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 | ![dom-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 | | |
| Rule | Description | Configurations | Fixable |
| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------ |
| [await-async-query](docs/rules/await-async-query.md) | Enforce async queries to have proper `await` | ![dom-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [await-async-utils](docs/rules/await-async-utils.md) | Enforce async utils to be awaited properly | ![dom-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][] | |
| [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 | ![dom-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [no-container](docs/rules/no-container.md) | Disallow the use of `container` methods | ![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-multiple-assertions-wait-for](docs/rules/no-multiple-assertions-wait-for.md) | Disallow the use of multiple expect inside `waitFor` | | |
| [no-node-access](docs/rules/no-node-access.md) | Disallow direct Node access | ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [no-promise-in-fire-event](docs/rules/no-promise-in-fire-event.md) | Disallow the use of promises passed to a `fireEvent` method | | |
| [no-wait-for-empty-callback](docs/rules/no-wait-for-empty-callback.md) | Disallow empty callbacks for `waitFor` and `waitForElementToBeRemoved` | ![dom-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 | ![dom-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-user-event](docs/rules/prefer-user-event.md) | Suggest using `userEvent` library instead of `fireEvent` for simulating user interaction | ![dom-badge][] ![angular-badge][] ![react-badge][] ![vue-badge][] | |
| [prefer-screen-queries](docs/rules/prefer-screen-queries.md) | Suggest using screen while using queries | ![dom-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][] |
| [prefer-screen-queries](docs/rules/prefer-screen-queries.md) | Suggest using screen while using queries | ![dom-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][] |
| [render-result-naming-convention](docs/rules/render-result-naming-convention.md) | Enforce a valid naming for return value from `render` | ![angular-badge][] ![react-badge][] ![vue-badge][] | |

[build-badge]: https://img.shields.io/travis/testing-library/eslint-plugin-testing-library?style=flat-square
[build-url]: https://travis-ci.org/testing-library/eslint-plugin-testing-library
Expand Down
77 changes: 77 additions & 0 deletions docs/rules/render-result-naming-convention.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Enforce a valid naming for return value from `render` (render-result-naming-convention)

> The name `wrapper` is old cruft from `enzyme` and we don't need that here. The return value from `render` is not "wrapping" anything. It's simply a collection of utilities that you should actually not often need anyway.

## Rule Details

This rule aims to ensure the return value from `render` is named properly.

Ideally, you should destructure what you need from `render`. In case you need to save the collection of utils returned in a variable, its name should be on of `view` or `utils`, as `render` is not wrapping anything: it's just returning a collection of utilities. Every other name for that variable will be considered invalid.
Belco90 marked this conversation as resolved.
Show resolved Hide resolved

To sum up these rules, the allowed naming convention for return value from `render` is:

- destructuring
- `view`
- `utils`

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

```javascript
import { render } from '@testing-library/framework';

// ...

// return value from `render` shouldn't be kept in a var called "wrapper"
const wrapper = render(<SomeComponent />);
```

```javascript
import { render } from '@testing-library/framework';

// ...

// return value from `render` shouldn't be kept in a var called "component"
const component = render(<SomeComponent />);
```

```javascript
import { render } from '@testing-library/framework';

// ...

// to sum up: return value from `render` shouldn't be kept in a var called other than "view" or "utils"
const somethingElse = render(<SomeComponent />);
```

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

```javascript
import { render } from '@testing-library/framework';

// ...

// destructuring return value from `render` is correct
const { unmount, rerender } = render(<SomeComponent />);
```

```javascript
import { render } from '@testing-library/framework';

// ...

// keeping return value from `render` in a var called "view" is correct
const view = render(<SomeComponent />);
```

```javascript
import { render } from '@testing-library/framework';

// ...

// keeping return value from `render` in a var called "utils" is correct
const utils = render(<SomeComponent />);
```

## Further Reading

- [Common Mistakes with React Testing Library](https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#using-wrapper-as-the-variable-name-for-the-return-value-from-render)
Belco90 marked this conversation as resolved.
Show resolved Hide resolved
7 changes: 6 additions & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ import preferPresenceQueries from './rules/prefer-presence-queries';
import preferScreenQueries from './rules/prefer-screen-queries';
import preferUserEvent from './rules/prefer-user-event';
import preferWaitFor from './rules/prefer-wait-for';
import noMultipleAssertionsWaitFor from './rules/no-multiple-assertions-wait-for'
import noMultipleAssertionsWaitFor from './rules/no-multiple-assertions-wait-for';
import preferFindBy from './rules/prefer-find-by';
import invalidRenderResultName from './rules/render-result-naming-convention';
Belco90 marked this conversation as resolved.
Show resolved Hide resolved

const rules = {
'await-async-query': awaitAsyncQuery,
Expand All @@ -38,6 +39,7 @@ const rules = {
'prefer-screen-queries': preferScreenQueries,
'prefer-user-event': preferUserEvent,
'prefer-wait-for': preferWaitFor,
'render-result-naming-convention': invalidRenderResultName,
};

const domRules = {
Expand All @@ -57,6 +59,7 @@ const angularRules = {
'testing-library/no-debug': 'warn',
'testing-library/no-dom-import': ['error', 'angular'],
'testing-library/no-node-access': 'error',
'testing-library/render-result-naming-convention': 'error',
};

const reactRules = {
Expand All @@ -65,6 +68,7 @@ const reactRules = {
'testing-library/no-debug': 'warn',
'testing-library/no-dom-import': ['error', 'react'],
'testing-library/no-node-access': 'error',
'testing-library/render-result-naming-convention': 'error',
};

const vueRules = {
Expand All @@ -74,6 +78,7 @@ const vueRules = {
'testing-library/no-debug': 'warn',
'testing-library/no-dom-import': ['error', 'vue'],
'testing-library/no-node-access': 'error',
'testing-library/render-result-naming-convention': 'error',
};

export = {
Expand Down
101 changes: 101 additions & 0 deletions lib/rules/render-result-naming-convention.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import { getDocsUrl, hasTestingLibraryImportModule } from '../utils';
import {
isCallExpression,
isIdentifier,
isImportSpecifier,
isObjectPattern,
isRenderVariableDeclarator,
} from '../node-utils';

export const RULE_NAME = 'render-result-naming-convention';

const ALLOWED_VAR_NAMES = ['view', 'utils'];
const ALLOWED_VAR_NAMES_TEXT = ALLOWED_VAR_NAMES.map(
name => '`' + name + '`'
).join(', ');

export default ESLintUtils.RuleCreator(getDocsUrl)({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description: 'TODO',
Belco90 marked this conversation as resolved.
Show resolved Hide resolved
category: 'Best Practices',
recommended: false,
},
messages: {
invalidRenderResultName: `\`{{ varName }}\` is not a recommended name for \`render\` returned value. Instead, you should destructure it, or call it using one of the valid choices: ${ALLOWED_VAR_NAMES_TEXT}`,
},
fixable: null,
schema: [
{
type: 'object',
properties: {
renderFunctions: {
type: 'array',
},
},
},
],
},
defaultOptions: [
{
renderFunctions: [],
},
],

create(context, [options]) {
const { renderFunctions } = options;
let renderResultName: string | null = null;
let renderAlias: string | undefined;

return {
ImportDeclaration(node: TSESTree.ImportDeclaration) {
Belco90 marked this conversation as resolved.
Show resolved Hide resolved
if (!hasTestingLibraryImportModule(node)) {
return;
}
const renderImport = node.specifiers.find(
node => isImportSpecifier(node) && node.imported.name === 'render'
);

if (!renderImport) {
return;
}

renderAlias = renderImport.local.name;
},
VariableDeclarator(node) {
const isValidRenderDeclarator = isRenderVariableDeclarator(node, [
...renderFunctions,
renderAlias,
]);

if (isValidRenderDeclarator && !isObjectPattern(node.id)) {
renderResultName = isIdentifier(node.id) && node.id.name;

const renderFunctionName =
isCallExpression(node.init) &&
isIdentifier(node.init.callee) &&
node.init.callee.name;

const isTestingLibraryRender =
!!renderAlias || renderFunctions.includes(renderFunctionName);
const isAllowedRenderResultName = ALLOWED_VAR_NAMES.includes(
renderResultName
);

if (isTestingLibraryRender && !isAllowedRenderResultName) {
context.report({
node,
messageId: 'invalidRenderResultName',
data: {
varName: renderResultName,
},
});
}
}
},
};
},
});
4 changes: 2 additions & 2 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ const LIBRARY_MODULES = [
];

const hasTestingLibraryImportModule = (node: TSESTree.ImportDeclaration) => {
return LIBRARY_MODULES.includes(node.source.value.toString())
}
return LIBRARY_MODULES.includes(node.source.value.toString());
};

const SYNC_QUERIES_VARIANTS = ['getBy', 'getAllBy', 'queryBy', 'queryAllBy'];
const ASYNC_QUERIES_VARIANTS = ['findBy', 'findAllBy'];
Expand Down
3 changes: 3 additions & 0 deletions tests/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Object {
"testing-library/prefer-find-by": "error",
"testing-library/prefer-screen-queries": "error",
"testing-library/prefer-user-event": "warn",
"testing-library/render-result-naming-convention": "error",
},
}
`;
Expand Down Expand Up @@ -64,6 +65,7 @@ Object {
"testing-library/prefer-find-by": "error",
"testing-library/prefer-screen-queries": "error",
"testing-library/prefer-user-event": "warn",
"testing-library/render-result-naming-convention": "error",
},
}
`;
Expand All @@ -90,6 +92,7 @@ Object {
"testing-library/prefer-find-by": "error",
"testing-library/prefer-screen-queries": "error",
"testing-library/prefer-user-event": "warn",
"testing-library/render-result-naming-convention": "error",
},
}
`;
Loading