27

I am using jest to test my reactJS component. In my reactJS component, I need to use jquery UI, so I added this in the component:

var jQuery = require('jquery');
require('jquery-ui/ui/core');
require('jquery-ui/ui/draggable');
require('jquery-ui/ui/resizable');

And it worked fine. But, now, I need to used jest to do testing, but I immediately meet this issue when I load the component into testutils,

Test suite failed to run
ReferenceError: jQuery is not defined 

Has anyone met this issue if you are using jQuery in your app?

Thanks

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
user3006967
  • 3,291
  • 10
  • 47
  • 72

3 Answers3

53

You can add jQuery dependency in your global object. Do the following

  1. In your package.json, under jest key add setupFiles like this "setupFiles": ["test-env.js"] For example:
{
  "jest": {
    "setupFiles": [ "<rootDir>/tests/test-env.js" ]
  }
}
  1. 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.

mrkwse
  • 420
  • 7
  • 16
mdsAyubi
  • 1,225
  • 9
  • 9
  • 4
    This answer worked for me better than any others. just a note on rootDir, it can be used as follows: "/test-env.js" my jest setup looked like the folowing: "jest": { ... "setupFiles": ["/test-env.js"] } – Dennis Baskin Aug 04 '17 at 08:19
  • In my case this approach not worked. But as soon as I set setupFiles via jest.config.js which I already had - everything became fine. – ydanila Dec 28 '20 at 09:51
0

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 bootstrap
global.$.fn.modal = jest.fn(() => $());
global.$.fn.carousel = jest.fn(() => $());
global.$.fn.tooltip = jest.fn(() => $());
Pulkit Goyal
  • 5,604
  • 1
  • 32
  • 50
0

The above answers didn't work for me. Only this worked:
Create a file called setupTests.js in your src folder and enter this:

import $ from 'jquery';
global.$ = $;
global.jQuery = $;

more info on this solution: here

rob9099
  • 19
  • 4