[Solved] Install and use testing frameworks - Mocha and Chai in WebStorm?

  

3
Topic starter

HI , I need to do some unit testing - to test my JavaScript code for errors.

I need to know how to install and configure unit testing frameworks like Mocha and Chai and maybe jsdom in WebStorm/PHPStorm?

Thanks!

1 Answer
2

The Unit Tests with Sinon and Mocha strategy gives you access to the following libraries to help you test your code - Mocha, Sinon, Chai, Sinon-Chai and jQuery.

Here is the intallation process (guide for installing and setting up the needed libraries and frameworks to allow local testing of JavaScript code and working with the DOM):

In order to test JS code easily we'll install the testing framework - Mocha and an assertion library to go with it - Chai.
Setting up testing of the DOM requires some additional libraries - jsdom to simulate the DOM and jsdom-global a small helper library which takes care of the jsdom setup for us. We'll also install jquery for easier manipulation of the DOM.

1. Install Mocha globally, we can do it from cmd or from the WebStorm/PHPStorm terminal (they're equivalent):

npm install -g Mocha

installing mocha

2. Install Chai globally (the same way as above):

npm install -g Chai

installing Chai testing framework

3. Install jsdom globally:

npm install –g jsdom

install jsdom

4. Install jsdom-global globally:

npm install –g jsdom-global

install jsdom globally

5. Install jquery globally:

npm install –g jquery

install jquery globally

Setup:

We can setup the libraries for global use by adding a NODE_PATH variable in the registries:

setx NODE_PATH %AppData%\npm\node_modules

set NODE_PATH=%AppData%\npm\node_modules

node paths for testing frameworks javascript

Usage:

In order to load and use a library we need to require it in the JavaScript file:

chai testing library usage

Keep in mind that jsdom-global requires you to have installed jsdom and must also be executed (thus the double brackets()). You also have to require jquery after the DOM has been loaded.

In order to set up the HMTL that is going to be used you can pass it as text to document.body.innerHTML as follows:

jsdom usage

Here's an example setup:

let expect = require('chai').expect;
let jsdom = require('jsdom-global')();
let $ = require('jquery');
 
document.body.innerHTML = `<div id="wrapper">
        <input type="text" id="name">
        <input type="text" id="income">
    </div>`;
 
let testedFunction = function () {
    //Some code
};
 
describe('testedFunction',function () {
    //Tests here
});
Share: