我正在使用 JsTestDriver 和一些 Jack(仅在需要时)。有谁知道如何验证单元测试期间是否已调用 JavaScript 函数?
E.g.
function MainFunction()
{
var someElement = ''; // or = some other type
anotherFunction(someElement);
}
并在测试代码中:
Test.prototype.test_mainFunction()
{
MainFunction();
// TODO how to verify anotherFunction(someElement) (and its logic) has been called?
}
Thanks.
JavaScript 是一种非常强大的语言,您可以在运行时更改行为。
您可以在测试期间将 anotherFunction 替换为您自己的函数并验证它是否已被调用:
Test.prototype.test_mainFunction()
{
// Arrange
var hasBeenCalled = false;
var old = anotherFunction;
anotherFunction = function() {
old();
hasBeenCalled = true;
};
// Act
MainFunction();
// Assert (with JsUnit)
assertEquals("Should be called", true, hasBeenCalled);
// TearDown
anotherFunction = old;
}
The note:您应该注意,此测试会修改全局函数,如果失败,则可能无法始终恢复它。
你可能最好选择JsMock http://jsmock.sourceforge.net/examples/为了那个原因。
但为了使用它,你需要将函数分开并将它们放入对象中,所以你不会有任何全局数据 at all.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)