如何在单元测试期间调用某个javascript函数 [英] How to verify a certain javascript function has been called during unit testing

查看:59
本文介绍了如何在单元测试期间调用某个javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JsTestDriver和一些Jack(仅在需要时)。有没有人知道如何验证在单元测试期间是否调用了javascript函数?

I'm using JsTestDriver and a bit of Jack (only when needed). Does anyone know how to verify that a javascript function has been called during unit testing?

例如

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是一种非常强大的语言,您可以在运行时更改行为。

您可以在测试期间用您自己的替换anotherFunction并验证它已被调用:

JavaScript is very powerful language in terms that you can change the behaviour at runtime.
You can replace anotherFunction with your own during test and verify it has been called:

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;
}

注释:你应该知道这个test会修改全局函数,如果它失败,它可能无法始终恢复它。

你最好选择 JsMock

但是为了使用它你需要将函数分开并将它们放入对象中,所以你 就没有了全局数据

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.
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.

这篇关于如何在单元测试期间调用某个javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆