jest: unresolved modules with eslint

2021-05-16

 | 

~2 min read

 | 

256 words

Unable to resolve path to module <xxx>. eslint(import/no-unresolved).

If you’re getting an unresolved module error like the one above from ESLint, it means that ESLint (and ESLint alone) is unable to resolve the module.

The good news is the code will still work (though if you have linting as part of your CI pipeline, your builds may fail). On the other hand, you don’t have any of the protection you would otherwise get from a linter, because we’re obfuscating an entire class of error.

How can we resolve this? Custom import resolver.

Let’s imagine that we’re getting this error in a test file and we’re using jest as our runner, then we’d reach for eslint-import-resolver-jest. More generally, ESLint has import resolvers for a number of tools - typescript, webpack, meteor, etc. Here’s a general search on NPM.

Configuring the resolver is a two step process:

  1. Install it
  2. Update the eslintrc to tell ESLint when to use it.

Installing The Resolver

We can add the resolver as a dev dependency like so:

% yarn add --dev eslint-import-resolver-jest

Updating .eslintrc

Updating the .eslintrc.js is done with overrides:

.eslintrc.js
const path = require('path')

module.exports = {
+   overrides: [
+     {
+       files: ['**/__tests__/**', '**/*.test.**'],
+       settings: {
+         'import/resolver': {
+           jest: {
+             jestConfigFile: path.join(__dirname, './jest.config.js'),
+           },
+         },
+       },
+     },
+   ],
}

With the dependency installed and the configuration updated, the error should disappear as ESLint is now able to resolve the module!


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!