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
2. Install Chai globally (the same way as above):
npm install -g Chai
3. Install jsdom globally:
npm install –g jsdom
4. Install jsdom-global globally:
npm install –g jsdom-global
5. Install jquery globally:
npm install –g jquery
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
Usage:
In order to load and use a library we need to require it in the JavaScript file:
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:
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 });