Skip to content

Commit

Permalink
fix: false negatives for no-dom-import with several imports
Browse files Browse the repository at this point in the history
Use the new refactored utils function to get a list of all testing-library imports
and make sure that none of them are a dom import.

Ref: testing-library#586
  • Loading branch information
sjarva committed Oct 1, 2022
1 parent 78a3d4e commit 6e2df31
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 13 deletions.
5 changes: 5 additions & 0 deletions docs/rules/no-dom-import.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ import { fireEvent } from 'dom-testing-library';
import { fireEvent } from '@testing-library/dom';
```

```js
import { render } from '@testing-library/react'; // Okay, no error
import { screen } from '@testing-library/dom'; // Error, unnecessary import from @testing-library/dom
```

```js
const { fireEvent } = require('dom-testing-library');
```
Expand Down
26 changes: 13 additions & 13 deletions lib/rules/no-dom-import.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { TSESTree } from '@typescript-eslint/utils';

import { createTestingLibraryRule } from '../create-testing-library-rule';
import { isCallExpression } from '../node-utils';
import { isCallExpression, getImportModuleName } from '../node-utils';

export const RULE_NAME = 'no-dom-import';
export type MessageIds = 'noDomImport' | 'noDomImportFramework';
Expand Down Expand Up @@ -84,22 +84,22 @@ export default createTestingLibraryRule<Options, MessageIds>({

return {
'Program:exit'() {
const importName = helpers.getTestingLibraryImportName();
const importNode = helpers.getTestingLibraryImportNode();
let importName: string | undefined;
const allImportNodes = helpers.getAllTestingLibraryImportNodes();

if (!importNode) {
return;
}
allImportNodes.forEach((importNode) => {
importName = getImportModuleName(importNode);

const domModuleName = DOM_TESTING_LIBRARY_MODULES.find(
(module) => module === importName
);
const domModuleName = DOM_TESTING_LIBRARY_MODULES.find(
(module) => module === importName
);

if (!domModuleName) {
return;
}
if (!domModuleName) {
return;
}

report(importNode, domModuleName);
report(importNode, domModuleName);
});
},
};
},
Expand Down
12 changes: 12 additions & 0 deletions tests/lib/rules/no-dom-import.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,5 +203,17 @@ ruleTester.run(RULE_NAME, rule, {
code: 'require("@testing-library/dom")',
errors: [{ messageId: 'noDomImport' }],
},
{
code: `
require("@testing-library/dom");
require("@testing-library/react");`,
errors: [{ line: 2, messageId: 'noDomImport' }],
},
{
code: `
import { render } from '@testing-library/react';
import { screen } from '@testing-library/dom';`,
errors: [{ line: 3, messageId: 'noDomImport' }],
},
],
});

0 comments on commit 6e2df31

Please sign in to comment.