Giter Site home page Giter Site logo

eslint-import-resolver-jest's Introduction

eslint-import-resolver-jest

"I like my testutils where I can see 'em" 🕵🏽‍♀️

If you're using jest and you have installed custom name mappings in your config via the moduleNameMapper config and you're using the wonderful eslint-plugin-import you might get yelled at by eslint:

grafik

(I oftentimes create an alias for the helpers I use for testing)

Let's fix this!

yarn add eslint-import-resolver-jest -D

or

npm i eslint-import-resolver-jest -D

If you are using the package.json config option from jest everything should _just work_™.

If you are using a separate config file for jest using the --config option you have to point this plugin to it, too (in your .eslintrc):

"settings": {
  "import/resolver": {
    "jest": {
      "jestConfigFile": "./jest.conf.json"
    }
  }
}

That's it!

If you want to ensure that this resolver only applies to your test files, you can use ESLint's overrides configuration option:

"overrides": [
  {
    "files": ["**/__tests__/**/*.js"],
    "settings": {
      "import/resolver": {
        "jest": {
          "jestConfigFile": "./jest.conf.json"
        }
      }
    }
  }
]

Note

It will only resolve the modules in your test files that you specified via testRegex or testMatch in your jest config.

Contributing

Create issues in this repo or get active yourself:

yarn test # npm test works, too

License

MIT

eslint-import-resolver-jest's People

Contributors

glennscottrocks avatar greenkeeper[bot] avatar hovsater avatar nwoltman avatar rdig avatar renovate-bot avatar ryanchristo avatar samtgarson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

eslint-import-resolver-jest's Issues

Remove isTestFile check?

I'm talking about this:

if (!isTestFile(jestConfig, file)) {
return NOTFOUND;
}

I'm running into a situation where I have a utility file that I use throughout my project's tests, and jest is configured to resolve to that file fine and therefore this plugin doesn't warn about that import.

However, for that utility file, if it tries to import things that jest will resolve, the rule fails because it's not a test file.

For example:

// my-util.js
// themes is in `src/themes.js` and jest is configured to resolve `src` via `moduleDirectories`
import themes from 'themes' // <-- error

I understand why we'd want to make sure people don't apply this resolver on non-test files, but with this it's giving me a false negative and it's not really reasonable for this plugin to determine whether a certain file could be run within the Jest context.

So instead I propose that we remove the isTestFile check and update the config docs to use ESLint's built-in overrides feature so people use that to make sure they're only running this setting on the applicable files.

Breaks linting for all imports in target directories

I am working through Kent C. Dodds' new javascript testing course. Below is a minorly reconfigured version of what he has by Section 4, part 11 (his code is here).

What behavior were you expecting?
The configured ESLint to properly allow 'global' imports as defined in my jest.config file.

What actually happened?
The override definition in my .eslintrc.js breaks ESLints ability to recognize any imports correctly in the targeted directories.

How can I reproduce it?
I clone Kent Dodds branch given above and open it in VSCode. ESLint throws errors.

What was your environment like?
Windows 10 Home
VSCode 1.28.2
npm: '6.4.1',
node: v8.12.0,

package.json:

{
  "name": "calculator",
  "version": "1.0.0",
  "description": "See how to configure Jest and Cypress with React, Babel, and Webpack",
  "main": "index.js",
  "scripts": {
    "test": "jest",
    "dev": "webpack-serve",
    "build": "webpack --mode=production",
    "postbuild": "cp ./public/index.html ./dist/index.html",
    "start": "serve --no-clipboard --listen 8080 dist",
    "lint": "eslint .",
    "format": "prettier \"**/*.js\" --write",
    "validate": "npm run lint && npm run test && npm run build",
    "setup": "npm run setup && npm run validate"
  },
  "keywords": [],
  "author": "Kent C. Dodds <[email protected]> (http://kentcdodds.com/)",
  "license": "GPL-3.0",
  "devDependencies": {
    "@babel/core": "^7.0.0-beta.51",
    "@babel/plugin-proposal-class-properties": "7.0.0-beta.51",
    "@babel/plugin-proposal-object-rest-spread": "7.0.0-beta.51",
    "@babel/plugin-syntax-dynamic-import": "7.0.0-beta.51",
    "@babel/preset-env": "^7.0.0-beta.51",
    "@babel/preset-react": "^7.0.0-beta.51",
    "babel-core": "7.0.0-bridge.0",
    "babel-loader": "^8.0.0-beta.4",
    "babel-plugin-dynamic-import-node": "^2.2.0",
    "babel-plugin-emotion": "^9.2.4",
    "css-loader": "^0.28.11",
    "eslint": "^5.0.1",
    "eslint-config-kentcdodds": "^14.0.0",
    "eslint-import-resolver-jest": "^2.1.1",
    "file-loader": "^1.1.11",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^23.6.0",
    "jest-emotion": "^9.2.11",
    "prettier": "^1.13.7",
    "prop-types": "^15.6.2",
    "react-testing-library": "^5.2.3",
    "serve": "^9.1.0",
    "style-loader": "^0.21.0",
    "webpack": "^4.12.0",
    "webpack-cli": "^3.0.8",
    "webpack-serve": "^1.0.4"
  },
  "dependencies": {
    "emotion": "^9.2.4",
    "emotion-theming": "^9.2.9",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-emotion": "^9.2.4",
    "react-loadable": "^5.4.0",
    "react-point": "^3.0.1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/kentcdodds/jest-cypress-react-babel-webpack.git"
  },
  "bugs": {
    "url": "https://github.com/kentcdodds/jest-cypress-react-babel-webpack/issues"
  },
  "homepage": "https://github.com/kentcdodds/jest-cypress-react-babel-webpack#readme"
}

My jest.config.js file in the project root:

const path = require('path');

module.exports = {
    testEnvironment: 'jest-environment-jsdom',
    moduleDirectories: [
        'node_modules',
        path.join(__dirname, 'src'),
        'shared',
        path.join(__dirname, 'test'),
    ],
    moduleNameMapper: {
        '\\.module\\.css$': 'identity-obj-proxy',
        '\\.css$': require.resolve('./test/style-mock.js'),
    },
    setupTestFrameworkScriptFile: require.resolve('./test/setup-tests.js'),
};

My eslintrc, also in the project root:

const path = require('path');

module.exports = {
    extends: [
        'kentcdodds',
        'kentcdodds/import',
        'kentcdodds/webpack',
        'kentcdodds/jest',
        'kentcdodds/react',
    ],
    rules: {
        'linebreak-style': 0,
        'global-require': 0,
        'eslint linebreak-style': [0, 'error', 'windows'],
    },
    overrides: [
        {
            files: ['**/__tests__/**'],
            settings: {
                'import/resolver': {
                    jest: {
                          jestConfigFile: path.join(__dirname, './jest.config.js'),
                    },
                },
            },
        },
    ],
};

Eslint-import-resolver-jest does not seem to gather the module directories correctly from the targeted jest config file. However, the override is apparently being applied, as ESLint throws an error for all imports, including for installed node modules (when the override is removed, the required node modules don't throw any linting errors, as expected).

import React from 'react';  // ESLint throws "unable to resolve path to module" for all three of these imports
import { render } from 'calculator-test-utils';
import CalculatorDisplay from '../calculator-display';

I cloned Dodds branch and experienced precisely the same issue, so I don't think I have made some minor mistake somewhere. Any idea what's going on here? Thanks all very much in advance for your help!

Cannot handle absolute paths in moduleNameMapper

I'm distributing a reusable piece of Jest config in a package, which provides a moduleNameMapper object that maps certain strings to paths in that package. I use absolute paths to make the resolution independent of the actual Jest root dir:

module.export = {
 moduleNameMapper: {
    '^something$': path.resolve(__dirname, './path/in/shared/package'),
   ...
  }
}

Jest can handle this, but eslint-import-resolver-jest does not expect the path to be absolute and always prepends jestConfig.importResolverProjectRoot.

function getAbsolutePath(jestConfig: JestConfig, filepath: Path): Path {
const replacedRoot = filepath.replace(
JEST_ROOT_DIR_PREFIX,
jestConfig.rootDir
);
if (path.isAbsolute(jestConfig.rootDir)) {
return replacedRoot;
}
return path.join(jestConfig.importResolverProjectRoot, replacedRoot);
}

I think, instead of checking whether jestConfig.rootDir is absolute, this case could be covered by checking if replacedRoot instead. Would you accept a PR along these lines?

Workaround

Currently, you can set rootDir to an absolute path in the Jest config which uses the reusable snippet to make it work:

 rootDir: require('path').resolve(__dirname),

An in-range update of eslint-plugin-prettier is breaking the build 🚨

The devDependency eslint-plugin-prettier was updated from 2.6.2 to 2.7.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-prettier is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 3 commits.

  • 869f56d Build: update package.json and changelog for v2.7.0
  • 38537ba Update: Support prettierignore and custom processors (#111)
  • 047dc8f Build: switch to release script package

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

<rootDir> in moduleNameMapper

Hey,

I'm not sure why it can't resolve my files with this config:

/test/unit/jest.conf.js

const path = require('path');

module.exports = {
  rootDir: path.resolve(__dirname, '../../'),
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },

Is this supported? I'm a little confused with how eslint-import-resolver-jest resolves paths if <rootDir> is part of the moduleNameMapper source.

I'm wildly guessing the resolved path includes the <rootDir> twice? Since, if I remove from the moduleNameMapper declaration it works fine.

Also Jest resolves just fine with both ways of configuring the moduleNameMapper

An in-range update of eslint-plugin-flowtype is breaking the build 🚨

The devDependency eslint-plugin-flowtype was updated from 2.50.0 to 2.50.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-flowtype is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Release Notes for v2.50.1

2.50.1 (2018-09-18)

Bug Fixes

  • make require-exact-type ignore indexers in map types (#354) (0722187)
Commits

The new version differs by 1 commits.

  • 0722187 fix: make require-exact-type ignore indexers in map types (#354)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Wrong root directory is used when config file is passed in

Problem

I'm running into a problem with how my Jest config and eslint config line up. If I disable the import/no-unresolved rule, my tests run file, Jest knows where imports are. If I add back the rule and remove rootDir: "..",, I get a validation error (seen below) from Jest. If I have both the rule and the rootDir, I get the rule error (seen below) from eslint.

The problem seems to be Jest expecting adjusting the root directory based on where the config file is placed, whereas this package adjusts the root directory based on where package.json is. I have a proposed solution after all the code/files.

Errors

Validation Error:

● Validation Error:

  Module <rootDir>/test/support/test-helper.js in the setupFiles option was not found.
         <rootDir> is: /Users/tom/Desktop/development/repos/traitify/traitify-widgets/test

  Configuration Documentation:
  https://jestjs.io/docs/configuration.html

Rule Error:

7:22 error Unable to resolve path to module 'support/helpers' import/no-unresolved

Code

Running tests with jest --config test/jest.config.js

Folder structure:

src/components/index.js
src/lib/index.js
test/.eslintrc
test/jest.config.js
test/components/index.test.js
test/lib/index.test.js
test/support/helpers.js
test/support/test-helper.js"
package.json

test/.eslintrc

{
  "extends": [
    "plugin:jest/recommended"
  ],
  "settings": {
    "import/resolver": {
      "jest": {
        "jestConfigFile": "./test/jest.config.js"
      },
      "webpack": {
        "config": "webpack.config.babel.js"
      }
    }
  }
}

test/jest.config.js

module.exports = {
  modulePaths: [
    "<rootDir>/src/",
    "<rootDir>/test/"
  ],
  rootDir: "..",
  setupFiles: [
    "<rootDir>/test/support/test-helper.js"
  ]
};

test/components/index.test.js

import "support/helper";

// Test stuff

Solution

I looked into the code and the solution for my problems seems to be adding after root = path.dirname(configFilePath) after line 76. The only problem with the solution is that it breaks 5 tests. I'm not familiar enough with the code or tests to know whether or not it's just tests that are broken, or if actual use-cases will have problems too.

jestConfig = require(configFilePath);

An in-range update of prettier is breaking the build 🚨

The devDependency prettier was updated from 1.14.2 to 1.14.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

prettier is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests failed on CircleCI (Details).

Release Notes for 1.14.3

🔗 Changelog

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Replaced the old Node.js version in your .nvmrc with the new one

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Tries to find Jest config in package dependencies

I'm maintaining a package that contains import statements in its Rollup outputs which are transpiled via Webpack in applications using the package. In the Jest tests of another package, I am importing things from this package:

// package-b/some-test.s
import {something} from 'package-a';

This works soon as I configure Jest to also Babel transpile package-a as proposes in this Jest issue

When running eslint I'm seeing the following error, though:

Error: jestConfigFile not found in /path/to/package-b/node_modules/package-a/jest.config.js

It looks like the Jest resolver is also applied to imports found in node module dependencies. Scoping the importer to tests as suggested in the README additions of #38 also does not change anything since the linted file determines resolvers - not the file currently parsed for import statements. #32 addresses the same issue, but makes it fail silently even if the Jest config in the root project cannot be found.

The workaround that I found is to reference the Jest config with an absolute path in eslintrc.js:

 "settings": {
    "import/resolver": {
      "jest": {
        "jestConfigFile": path.resolve(__dirname, "./jest.config.js")
      }
    }
  }

I would have expected a relative jestConfigFile path to always be resolved relative to the .eslintrc.js file, not the package root of the file currently parsed for imports.

I'm mainly leaving this here as future reference for others.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.