How to import a JQuery plugin in a Jest test

Abou Kone
2 min readSep 25, 2018

--

My app is set up to use Jest to run my tests. Some of the application code makes use of JQuery SlimScroll so initially in order to make this plugin work with Angular I had to:

Add in src/typings.d.ts...interface JQuery {    easyPieChart;    slimScroll;}

And in my component I used it as :

import {Directive, Input, Output, ElementRef, EventEmitter} from '@angular/core';import 'jquery-slimscroll';@Directive({selector: '[baSlimScroll]'})export class BaSlimScroll {@Input() public baSlimScrollOptions: Object;constructor(private _elementRef: ElementRef) {}ngOnChanges(changes) {
this._scroll();
}
private _scroll() {
this._destroy();
this._init();
}private _init() {jQuery(this._elementRef.nativeElement)
.slimScroll(this.baSlimScrollOptions);
}

This works fine but trying to test any other component that uses has Jest fail with:

Test suite failed to runTypeError: Cannot read property 'fn' of undefined5 | global.$ = global['jQuery'] = $;
6 |
> 7 | import 'jquery-slimscroll';
| ^
8 |
9 |
at node_modules/jquery-slimscroll/jquery.slimscroll.js:10:5
at Object.<anonymous> (node_modules/jquery-slimscroll/jquery.slimscroll.js:474:3)
at Object.<anonymous> (src/setup-jest.ts:7:1)

The issue what when trying to import jquery-slimscroll , the library expected the $ JQuery global variable to exist already. I just updated my Jest setup file to look like:

// Import all global libraries here
import * as $ from 'jquery';
global['$'] = global['jQuery'] = $;
import 'jest-preset-angular';
import './jest-global-mocks';

This ensures the JQuery library has been added before trying to load the plugin.

That was some hard reading. Reward yourself now with some Nayanka Bell!

--

--

Abou Kone

Chief Mercenary @akiltechnologies. @codedivoire founder. African Tech is on my mind.