Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require jQuery plugin in jest test file?

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.

like image 879
kapantzak Avatar asked Mar 08 '23 05:03

kapantzak


1 Answers

package.json configuration:

"jest": {
        "setupFiles": ["./source/setup-jest.js"]
 },

source/setup-jest.js configuration:

import $ from 'jquery';
global.$ = $;
global.jQuery = $;
like image 90
Shubham Kumar Avatar answered Mar 19 '23 08:03

Shubham Kumar