Reputation: 3545
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
Upvotes: 27
Views: 17050
Reputation: 69
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
Upvotes: 0
Reputation: 5654
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(() => $());
Upvotes: 1
Reputation: 1245
You can add jQuery dependency in your global
object. Do the following
package.json
, under jest
key add setupFiles
like this
"setupFiles": ["test-env.js"]
For example:{
"jest": {
"setupFiles": [ "<rootDir>/tests/test-env.js" ]
}
}
test-env.js
look like thisimport $ from 'jquery';
global.$ = global.jQuery = $;
Make sure the path to test-env.js
is correct from your root directory. <rootDir>
is available in Jest.
Upvotes: 53