[英]How to verify a certain javascript function has been called during unit testing
I'm using JsTestDriver and a bit of Jack (only when needed). 我正在使用JsTestDriver和一些Jack(仅在需要时)。 Does anyone know how to verify that a javascript function has been called during unit testing?
有没有人知道如何验证在单元测试期间是否调用了javascript函数?
Eg 例如
function MainFunction()
{
var someElement = ''; // or = some other type
anotherFunction(someElement);
}
And in the test code: 并在测试代码中:
Test.prototype.test_mainFunction()
{
MainFunction();
// TODO how to verify anotherFunction(someElement) (and its logic) has been called?
}
Thanks. 谢谢。
JavaScript is very powerful language in terms that you can change the behaviour at runtime. JavaScript是一种非常强大的语言,您可以在运行时更改行为。
You can replace anotherFunction with your own during test and verify it has been called: 您可以在测试期间用您自己的替换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 : You should be aware that this test modifies the global function and if it will fail it may not always restore it. 注意 :您应该知道此测试会修改全局函数,如果它失败,它可能无法始终恢复它。
You'd probably better pick JsMock for that. 你最好选择JsMock 。
But in order to use it you need to separate the functions and put them into objects, so you would not have any global data at all. 但是为了使用它,你需要将函数分开并将它们放入对象中,这样你根本就不会有任何全局数据 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.