Jest doesn't work with global jquery
volodyad opened this issue · comments
I have setup jest with webpack according to articles from https://facebook.github.io/jest/docs/getting-started.html. All works fine except I have got third party libraries which requires reference to global jquery. I have configured webpack in the next way
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
so it works when I run my app, but when I try to run test it says jQuery is not defined. What can I do with this issue?
You can load jQuery in a setup file, see https://facebook.github.io/jest/docs/api.html#config-setupenvscriptfile-string
window.$ = require('path/to/jquery');
for example.
In package.json:
"jest": {
"setupFiles": ["./source/setup-jest.js"]
},
In source/setup-jest.js
import $ from 'jquery';
global.$ = global.jQuery = $;
Thanks for that @charliecalvert -- Been trying to wire up unit tests to my clients Shopify store repo, this helped a lot!
In package.json:
"jest": { "setupFiles": ["./source/setup-jest.js"] },In source/setup-jest.js
import $ from 'jquery'; global.$ = global.jQuery = $;
Worked for me as well, thank you!
In package.json:
"jest": { "setupFiles": ["./source/setup-jest.js"] },In source/setup-jest.js
import $ from 'jquery'; global.$ = global.jQuery = $;Worked for me as well, thank you!
Doesn't work for me!
setting up my setup-jest.js
file with
import $ from 'jquery';
global.$ = global.jQuery = $;
Does not work for me either. I'm trying to run a test for my bootstrap Modal and says that modal is not a function.
This works for me:
global.jQuery = require('jquery');
global.$ = global.jQuery;
If it's not working for you, make sure you're not using ES import
and export
statements as those are hoisted to the top of the file. Therefore, if you set something on the window
/global
, it won't apply to subsequent import
s. Things will execute in the order you expect if you use require
statements.
What worked for me, was adding bootstrap
to transformIgnorePatterns
in jest.config
as suggested in this post.
transformIgnorePatterns: [
"<rootDir>/node_modules/(?!bootstrap/)",
],
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.