I have included js libraries like jQuery, moment from CDN in my index.html to make sure my app is less in size and should not include external libraries.
As I included moment library in index.html, I'm able to make use of moment() function in my components.
But, I'm getting following error when I'm performing unit tests.
ReferenceError: moment is not defined
Is there any support to include external libraries or this is a new feature?
You can create a file and add it to "setupFiles": ["path/to/setup.js"] and put something like global.moment = require('moment'); into it, for example.
Thanks @cpojer for the quick update. Does require('moment'); needs node module to be installed in the project? which don't want to do eventually.
You can point it to your JS file: require('path/to/moment'). You can try to do this:
require('path/to/moment')
console.log(global.moment);
or
global.moment = require('path/to/moment')
console.log(global.moment);
and see which one works. I'm not familiar with moment myself.
Thanks @cpojer, second one is working for me.
global.moment = require('path/to/moment')
console.log(global.moment);
Is it possible to use libraries directly from CDN instead of downloading to local system and referring it?
I would advice against making network connections in your test code.
It usually leads to slow and flaky tests, which will mean developing your project is slower.
@cpojer I know you advice against it but is it possible use libraries directly from CDN in jest? If so how? Struggling very hard to do this and this thread is the closest info I have found to a solution
I have a similar question to @TannerQuigley: how do I reference files hosted on a CDN?
And these are not my project files but rather a 3rd party vendor library.
Same question here, if I have for example
index.html
<script src="external-library.js" />
Component.js
import { Button } from 'external-library' // this is posible with rollup globals or webpack externals
Test fails because it cannot resolve external-library
โ Test suite failed to run
Cannot find module 'external-library' from 'Component.js'
@b0ric @TannerQuigley
You can use RequireJS if it's really essential.
@cpojer
I don't get this working with require('..') and setupFiles. I'm using ts-jest though but need my ts file having referenced a js library. I've put the path to the js library into the setupFiles array but no luck so far. Any ideas?
require('../../src/lib/lib.js'); (actual path of test referencing the library)
setupFiles: ["./src/lib/lib.js"] (jest.config.js in root referencing the library)
Most helpful comment
It usually leads to slow and flaky tests, which will mean developing your project is slower.