reactjs jest jQuery is not defined
You can add jQuery dependency in your global
object. Do the following
- In your
package.json
, underjest
key addsetupFiles
like this"setupFiles": ["test-env.js"]
For example:
{ "jest": { "setupFiles": [ "<rootDir>/tests/test-env.js" ] }}
- Where the contents on
test-env.js
look like this
import $ from 'jquery';global.$ = global.jQuery = $;
Make sure the path to test-env.js
is correct from your root directory. <rootDir>
is available in Jest.
If you are using Jest 27+, node is now the default testEnvironment
. If you need to use jQuery in jest setup script, make sure to first change the testEnvironment
back to jsdom
.
in jest.config.js
:
module.exports = { setupFilesAfterEnv: ['./jest.setup.js'], testEnvironment: 'jsdom'}
in jest.setup.js
:
import $ from 'jquery';global.$ = $;global.jQuery = $;// If you want to mock bootstrapglobal.$.fn.modal = jest.fn(() => $());global.$.fn.carousel = jest.fn(() => $());global.$.fn.tooltip = jest.fn(() => $());