Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest not able to load underscore

Getting error TypeError: Cannot read property '_' of undefined

at line import _ from 'underscore';

when running Jest-React testcase.

like image 727
Hina Dawood Avatar asked Feb 09 '18 00:02

Hina Dawood


People also ask

How does jest recognize a test file?

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 .

What is transformIgnorePatterns?

The transformIgnorePatterns option can be used to whitelist or blacklist files from being transformed with babel.

What is preset in jest?

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.

Do you need to import jest?

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.


3 Answers

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.

like image 88
Nufayl Avatar answered Oct 16 '22 17:10

Nufayl


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._ = _
like image 44
HRHeeb Avatar answered Oct 16 '22 16:10

HRHeeb


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
    }
};
like image 2
Bhaskar Avatar answered Oct 16 '22 18:10

Bhaskar