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
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With