I have react application with npm and webpack. I'm trying to add unit testing to it.
I'm using jQuery from CDN included in my index.html rather than using node module.
I'm using jQuery in a Component Test1
to which I added Unit test cases.
Now, when I'm executing test cases I'm getting error saying
ReferenceError: $ is not defined
I understand that Jest is not able to resolve it as I didn't import jQuery import in Component.
Question is, How to let Jest know about external JS?
We can make use of "setupFiles" configuration to allow Jest to execute all scripts / libraries / modules required before start executing tests.
Create and add a file to "setupFiles": ["path/to/setup.js"] and include your library into that.
For example,
global.jQuery = global.$ = require('path/to/jQuery')
Please find my query posted on Jest github repo.
There are a few ways to achieve this. I prefer to use Require.js, though you may already be using another bundler like Browserify or Webpack—that should work too. A good quick-start with Require.js is this example project. In short, set up Require.js with your CDN files, reference the bundled result in your front-end, hook Require.js into your tests and then require()
them just as you do your other node modules.