Reputation: 11750
I have developed a simple jQuery plugin and I want to perform some automated testing using facebook's jestjs framework.
The plugin is a self executed function:
Plugin code
; (function ($, window, document, undefined) {
var pluginName = 'searchAreaControl';
function Plugin(element, options) {
this.el = element;
this.$el = $(element);
this.opt = $.extend(true, {}, $.fn[pluginName].defaults, options);
this.rootClassName = 'elem-searchAreaControl';
this.popupID = null;
this.init();
}
Plugin.prototype = {
...
}
// Methods ...
})(jQuery, window, document);
The project's folder structure is like this:
Root
|
+-- __test__
| |
| +-- sum.test.js
|
+-- searchAreaControl
| |
| +-- css
| +-- searchAreaControl.js
|
+-- node_modules
|
// And other folders
sum.test.js (Jest test)
jest.dontMock('jquery').dontMock('searchAreaControl');
var $ = require('jquery');
var searchAreaControl = require('../searchAreaControl/searchAreaControl');
test('Initialize plugin', function() {
document.body.innerHTML = '<button id="myButton" class="elem-searchAreaControl" type="button"></button>';
$('#myButton').searchAreaControl();
expect($('#myButton').hasClass('elem-searchAreaControl')).toEqual(true);
});
In the test file, I create a button element and try to initialize the searchAreaControl
plugin on it. I expect that, after the initialization, this button element will have the class elem-searchAreaControl
.
I run
npm test
And I get this error:
Cannot find module 'searchAreaControl' from 'sum.test.js'
As soon as searchAreaControl.js
is not a module I suppose I cannot use require('searchAreaControl')
. Does anyone have the experience to indicate a solution?
Here is the full code Github repo.
Upvotes: 8
Views: 9763
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.$ = $;
// If you want to mock bootstrap
global.$.fn.modal = jest.fn(() => $());
global.$.fn.carousel = jest.fn(() => $());
global.$.fn.tooltip = jest.fn(() => $());
If you are using TypeScript, in a global typings file (e.g. global.d.ts
at the root of your project), add:
interface Window {
$: typeof import('jquery');
}
Upvotes: 1
Reputation: 101
package.json configuration:
"jest": {
"setupFiles": ["./source/setup-jest.js"]
},
source/setup-jest.js configuration:
import $ from 'jquery';
global.$ = $;
global.jQuery = $;
Upvotes: 10
Reputation: 89
I create setup-jest.js
global.window = window
global.$ = require('jquery');
in package.json
"jest": {
"setupFiles": ["./setup-jest.js"]
}
and then it's automatic require jQuery when start npm test
Upvotes: 6