Is it possible to test a .each(function()) statement?

162 Views Asked by At

I am attempting to test a javascript function. I am using jquery, sinon and running jsTestDriver.jstd in PhpStorm.

I have two different scenarios where I need to test .each(function()).

Scenario 1: My issue is that I need to test a function that uses a $(tagname).each(function()) line as it's function.

I tried using sinon to stub either $(tagname) or $(tagname).each(). The first returned a TypeError: $(...).each is not a function. The second didn't cause errors but I need to test what happens after the ORIGINAL each() not my stub which this does not do.

Code being tested:

function updateID(){
 $('div.monthpicker_input').each(function(){
    console.log("this is not called via testing");
    let id = this.parentNode.parentNode.htmlFor;
    id=id+"Input";
    this.id=id;
});
}

Relevant part of the testing code:

ActionsTestDate.prototype.testUpdateID = function () {
 var before =  $('div.monthpicker_input').each().id;
 updateID();
 var after = $('div.monthpicker_input').each().id;
 assertNotEquals(before, after);
};

ActionsTestDate.prototype.setUp = function() {
 var monthPicker = {
     id: "",
     parentNode: {
        parentNode: {
            htmlFor: "TestHtml"
        }
     }
  };

var the$ = sinon.stub(window, '$');
the$.withArgs('div.monthpicker_input').returns({
    monthPicker/*,
    each: function (a) {
     // a();
        return monthPicker
     }
 */
});
 };

ActionsTestDate.prototype.tearDown = function() {
  window.$.restore();
 };

I expect the id to change. It does not.

Scenario 2: I am testing a d3.selectAll(className).each(function()) statement.

I have quite a few of these.

An example:

d3.selectAll(".light").each(function() {  //light regions
    this.style['fill']= 'white';
    this.style['opacity']= 1;
    this.style['backgroundColor']= 'white';
    this.style['color']= 'white';
});

Another Example:

window.d3.selectAll(".c3-legend-item-hidden").each(function() {
    this.style['opacity']= 0.15;
});

Testing:

var d3selectAllWas = sinon.spy(window.d3, 'selectAll');
functionCalledHere();
assert(d3selectAllWas.calledWith(".light"));  //is true

I am just using sinon spy for selectAll at the moment but it doesn't do the function as selectAll doesn't return anything in tests.

Versions I am using:

jQuery JavaScript Library v1.11.1

Sinon version 7.3.2, 2019-04-17

D3 v5.9.7

C3 v0.7.2

0

There are 0 best solutions below