Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject external JS from CDN to Jest unit testing?

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?

like image 343
pgollangi Avatar asked Nov 02 '16 14:11

pgollangi


People also ask

How do I load a script in Jest?

You load an external script in Jest by using Node's require() function, passing it the relative path to the script file you wish to load (this script must be saved locally): //load the `index. js` file require('../js/index.

Does Jest use Jsdom?

Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment setting. If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run.

Can Jest be used for unit testing?

Jest is a Javascript Testing Framework by Facebook. It is used most commonly for unit testing. Unit testing is when you provide input to a unit of code(usually, a function) and match the output with the expected output.

Can I use Jest for API testing?

Jest is great for validation because it comes bundled with tools that make writing tests more manageable. While Jest is most often used for simple API testing scenarios and assertions, it can also be used for testing complex data structures.


1 Answers

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.

like image 123
pgollangi Avatar answered Sep 16 '22 19:09

pgollangi