首页 > 解决方案 > 是否可以测试 .each(function()) 语句?

问题描述

我正在尝试测试一个 javascript 函数。我在 PhpStorm 中使用 jquery、sinon 和运行 jsTestDriver.jstd。

我有两个不同的场景需要测试 .each(function())。

场景 1:我的问题是我需要测试一个使用 $(tagname).each(function()) 行作为函数的函数。

我尝试使用 sinon 来存根 $(tagname) 或 $(tagname).each()。第一个返回一个 TypeError: $(...).each 不是一个函数。第二个没有导致错误,但我需要测试 ORIGINAL each() 之后发生的事情,而不是我的存根,这不会发生。

正在测试的代码:

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;
});
}

测试代码的相关部分:

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();
 };

我希望 id 会改变。它不是。

场景 2:我正在测试一个d3.selectAll(className).each(function())语句。

我有很多这样的。

一个例子:

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

另一个例子:

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

测试:

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

我目前只是在 selectAll 中使用 sinon spy,但它没有执行该功能,因为 selectAll 在测试中没有返回任何内容。

我正在使用的版本:

jQuery JavaScript 库 v1.11.1

诗乃7.3.2版,2019-04-17

D3 v5.9.7

C3 v0.7.2

标签: javascriptjquerytestingsinonjs-test-driver

解决方案


推荐阅读