Jest cannot find module


#1

I’m trying to convert a project that currently uses karma for unit tests and I am running into an issue I believe is due to a module defined in aurelia.json with a name that does not correspond to the npm package name:

jest is failing with

Cannot find module ‘zxing’ from ‘scanner.ts’

This seems to suggest that jest isn’t set up to use aurelia.json for module resolution. Is this the expected case? Or am I just missing some configuration somewhere?


#2

This is troublesome. The existing karma+jasmine setup uses the same bundle file to run in browser.

jest is different, it purely runs in nodejs but simulate a browser environment (create global vars based on jsdom).

So the module resolution is nodejs in jest. This issue is not limited to cli bundler, but also if you use webpack to build your code.

jest doc has a whole section how to deal with webpack module resolution. https://jestjs.io/docs/en/webpack

You might be able to teach jest with

"moduleNameMapper": {
      "^zxing$": "<rootDir>/node_modules/instascan",
    }

BTW, it looks you are still using an very old version of cli bundler. If you upgrade to latest cli, you can remove lots of dependencies in aurelia.json, they can be auto traced.


#3

thanks for pointing me in the right direction, that fixed the zxing issue and I was also able to suppress another warning I was seeing,

WARN [array-observation] Detected 2nd attempt of patching array from Aurelia binding. This is probably caused by dependency mismatch between core modules and a 3rd party plugin. Please see https://github.com/aurelia/cli/pull/906 if you are using webpack.
"moduleNameMapper": {
      "^aurelia-binding$": "<rootDir>/node_modules/aurelia-binding/dist/commonjs/aurelia-binding.js"
    },

seemed to fix it.


#4

Thanks. That aurelia-binding thing is due to the troublesome v1+v2 dependencies. We had that issue in webpack previously, and fixed by patching webpack config with

resolve: {
    // Enforce single aurelia-binding, to avoid v1/v2 duplication due to
    // out-of-date dependencies on 3rd party aurelia plugins
    alias: { 'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding') }
  },

We need to add your patch to our jest config too. Thx!