Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use scoped packages with Jest

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

like image 493
Armando Avatar asked Aug 30 '17 13:08

Armando


1 Answers

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"
  }
}
like image 92
Dan Caddigan Avatar answered Sep 28 '22 09:09

Dan Caddigan