9

I am developing an app with react-native and typescript and doing the tests with Jest, but I have a problem when I use scoped packages (@assets), jest can not find the path and gives error.

The directory structure looks like this:

project/
  assets/
    img/
      foo.png
    package.json
  src/
    Foo.ts
  build/
    Foo.js


// assets/package.json
{
  "name": "@assets" // My @assets scope
}

// build/Foo.js
const image = require('@assets/img/foo.png'); // <- error in Jest

So when I run the jest:

npm run jest build/

It can not find '@assets/img/foo.png' and throws the error:

Cannot find module '@assets/img/logo.png' from 'Foo.js'

How can I use scope package in Jest?

Jest version: 20.0.4

thanks

Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34
Armando
  • 603
  • 1
  • 5
  • 14
  • erm. it won't care if you have a `package.json` in a subfolder if you have not got it in `node_modules` and `npm install`ed / `link`ed it. you can still get it to work via webpack aliases, see https://webpack.js.org/configuration/resolve/ – Dimitar Christoff Aug 30 '17 at 14:59
  • @DimitarChristoff, thanks dude, i found the `moduleNameMapper` that i can put in jest config. – Armando Aug 30 '17 at 20:06

2 Answers2

13

For those that get here that are using private packages under a scoped org, here's how I tackled this:

"jest": {
  "moduleNameMapper": {
    "^@org-name/(.*)$": "<rootDir>/node_modules/@org-name/$1/dist/$1.es5.js"
  }
}

This assumes that all of your scoped packages have a similar path to their exported module. If they don't, you can specify them individually:

"jest": {
  "moduleNameMapper": {
    "^@org-name/package-one$": "<rootDir>/node_modules/org-name/package-one/dist/package.js",
    "^@org-name/package-two$": "<rootDir>/node_modules/org-name/package-two/build/index.js"
  }
}
Dan Caddigan
  • 1,578
  • 14
  • 25
0

Necessary only define the moduleNameMapper in jest config:

// package.json
"jest": {
  "moduleNameMapper": {
      "^@assets.+\\.(png)$": "<rootDir>/assetsTransformer.js"
  },
}

// assetsTransformers.js
const path = require('path');

module.exports = {
  process(src, filename, config, options) {
    return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
  },
};

Thanks for this comment :-)

Armando
  • 603
  • 1
  • 5
  • 14