javascript - 是否可以测试 .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
解决方案
推荐阅读
- c++ - 连接失败时如何防止端口更改
- git - Git 无法更新带有致命标签的标签:标签“v0.0.8”已经存在
- css - FIORI 自定义主题被一些用户的 library.css 部分覆盖
- angularjs - 为什么angularjs在使用promise构造时会抛出“非法调用”?
- java - 有没有办法找到高于和低于平均水平的方法
- laravel - 如何使用laravel中的多个关系将记录保存在数据库中
- python - 有人可以解释在数据帧上使用循环的直觉吗?
- c# - 如何跳过数组的每个第三个元素
- angular - 在 Angular 中清除浏览器缓存
- excel - 在不知道确切名称的情况下打开工作簿