我正在使用 JsTestDriver 和一些 Jack(仅在需要时使用)。有谁知道如何验证在单元测试期间是否调用了 javascript 函数?
例如
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?
}
谢谢。
最佳答案
JavaScript 是一种非常强大的语言,您可以在运行时更改行为。
您可以在测试期间用您自己的函数替换另一个函数并验证它是否已被调用:
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;
}
注意:你应该知道这个测试修改了全局函数,如果它会失败,它可能不会总是恢复它。
你最好选择 JsMock为此。
但是为了使用它,您需要将函数分开并将它们放入对象中,因此您根本不会有任何全局数据。
关于javascript - 如何在单元测试期间验证已调用某个javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1787107/