简体   繁体   English

如何在单元测试期间调用某个javascript函数

[英]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.

相关问题 Javascript单元测试Jasmine /单元测试-如何测试是否已调用私有函数? - Javascript Unittesting Jasmine / Unit Testing - how do I test whether a private function has been called? 如何监视Jest单元测试是否已使用某个功能的javascript? - How spy whether a function has been used or not with Jest unit testing for javascript? 如何验证嘲笑已被调用 - How to verify that mockjax has been called 单元测试是否已在文档就绪时调用 localStorage.getItem? - Unit testing that localStorage.getItem has been called on document ready? 如何验证客户端上的Javascript是否未更改 - How to verify that Javascript on client has not been altered 识别函数如何在闭包javascript中调用 - Identify how the function has been called in closure javascript 如何检测具有特定签名的JavaScript函数? - How to detect a JavaScript function with a certain signature has been registered? 如何使用sinon验证clearInterval? - How do I verify clearInterval has been called with sinon? 将鼠标放在div上一定时间后,如何调用一个函数? - How do you have a function called after the mouse has been on a div for a certain amount of time? 您将如何实现javascript函数,以使其具有被调用多少次的概念? - How would you implement a javascript function so that it has a notion of how many times it has been called?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM