【发布时间】:2013-01-23 11:39:59
【问题描述】:
单元测试的正确语法是什么?
当我在浏览器中打开它时,以下内容有效。目的是在输入框 ib 更改时读取其内容,并将其解释值写入表格单元格 c5 ...
var c5 = document.createElement('td');
var ib = document.createElement('input');
// For all browsers except IE before Version 9 -see http://help.dottoro.com/ljeuqqoq.php
if (ib.addEventListener)
{
ib.addEventListener('change', Action01InputBox (ib, c5), false);
}
// For IE before Version 9 -see http://help.dottoro.com/ljeuqqoq.php
else {
if (ib.attachEvent){
ib.addEventListener('change', Action01InputBox (ib, c5), false);
}
}
这里是事件监听器。当然,它返回一个函数。
注意函数EmptyNode(c5) 只是删除目标节点的所有内容,RealNumberFromInput (ib.value) 通过正则表达式从输入字符串中获取一个实数...
function Action01InputBox (ib, c5)
{
return function ()
{
EmptyNode(c5);
var r = RealNumberFromInput (ib.value);
c5.appendChild(document.createTextNode(r));
};
};
这是单元测试...
Action01InputBoxTest = TestCase("Action01InputBoxTest");
Action01InputBoxTest.prototype.test01 = function()
{
// Text box
var r = 0.123;
var ib = document.createElement('input');
ib.setAttribute('value', document.createTextNode(r));
// Target cell
var c5 = document.createElement('td');
c5.appendChild(document.createTextNode("Bogus"));
// Do action
Action01InputBox(ib, c5);
assertEquals(c5.textContent, r);
};
c5 的 textContent 应该已经从“Bogus”更改为“0.123”,因此测试失败。
如果我理解正确的话,问题是测试调用了事件侦听器的返回值,而不是函数,但是我无法从测试中弄清楚如何正确调用函数。
提前致谢。
【问题讨论】:
标签: javascript unit-testing addeventlistener