Getting error TypeError: Cannot read property '_' of undefined
at line import _ from 'underscore';
when running Jest-React testcase.
The glob patterns Jest uses to detect test files. By default it looks for . js and . jsx files inside of __tests__ folders, as well as any files with a suffix of .
The transformIgnorePatterns option can be used to whitelist or blacklist files from being transformed with babel.
preset [string]A preset that is used as a base for Jest's configuration. A preset should point to an npm module that exports a jest-preset. json module on its top level.
In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them.
I have run into same error, hope this answer will help. To load an external modules / library into your Jest test suite. first you have to configure the test set up, see the example here.
see more under setupFiles
// jest.config.js
module.exports = {
setupFiles : ["./setup-jest.js"]
}
// setup-jest.js
import lodash from 'lodash'
global._ = lodash
Instead lodash you can use underscore or any modules / library. Hope this will help.
The following works for me:
I do not like to have a jest.config.js file, so I use the configuration in package.json:
"jest": {
"setupFilesAfterEnv": ["<rootDir>/setupJest.js"],
...
}
And in setupJest.js:
import _ from "underscore"
global._ = _
You can just configure the same in the jest.config.js
itself, (No need of another file)
const lodash = require('lodash')
module.exports = {
...
globals: {
'_': lodash
}
};
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