Skip to content

Commit

Permalink
Fix no-import-test-files rule incorrectly reporting module names en…
Browse files Browse the repository at this point in the history
…ding in `.js` (#226)
  • Loading branch information
GMartigny authored and sindresorhus committed May 14, 2019
1 parent 521d009 commit c383cf6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
11 changes: 10 additions & 1 deletion rules/no-import-test-files.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ const pkgUp = require('pkg-up');
const multimatch = require('multimatch');
const util = require('../util');

const externalModuleRegExp = /^\w/;
function isExternalModule(name) {
return externalModuleRegExp.test(name);
}

function isTestFile(files, rootDir, sourceFile, importedFile) {
const absoluteImportedPath = path.resolve(path.dirname(sourceFile), importedFile);
const relativePath = path.relative(rootDir, absoluteImportedPath);
Expand All @@ -23,8 +28,12 @@ function getProjectInfo() {

function createImportValidator(context, files, projectInfo, filename) {
return (node, importPath) => {
const isImportingTestFile = isTestFile(files, projectInfo.rootDir, filename, importPath);
const isImportingExternalModule = isExternalModule(importPath);
if (isImportingExternalModule) {
return;
}

const isImportingTestFile = isTestFile(files, projectInfo.rootDir, filename, importPath);
if (isImportingTestFile) {
context.report({
node,
Expand Down
27 changes: 16 additions & 11 deletions test/no-import-test-files.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,22 @@ const rootDir = path.dirname(__dirname);
const toPath = subPath => path.join(rootDir, subPath);

util.getAvaConfig = () => ({
files: ['lib/*.test.js']
files: [
'lib/*.test.js',
'test/**/*.js'
]
});

ruleTester.run('no-import-test-files', rule, {
valid: [
'import test from \'ava\';',
'const test = require(\'ava\');',
'console.log()',
'const value = require(somePath);',
'var highlight = require(\'highlight.js\')',
{
code: 'import test from \'ava\';'
},
{
code: 'const test = require(\'ava\');'
},
{
code: 'console.log()'
},
{
code: 'const value = require(somePath);'
code: 'var highlight = require(\'highlight.js\')',
filename: toPath('test/index.js')
}
],
invalid: [
Expand All @@ -45,6 +45,11 @@ ruleTester.run('no-import-test-files', rule, {
code: 'import test from \'./foo.test.js\';',
filename: toPath('lib/foo.js'),
errors: [{message: 'Test files should not be imported'}]
},
{
code: 'import test from \'./bar.js\';',
filename: toPath('test/foo.js'),
errors: [{message: 'Test files should not be imported'}]
}
]
});

0 comments on commit c383cf6

Please sign in to comment.