【问题标题】:How to verify a certain javascript function has been called during unit testing如何在单元测试期间验证某个javascript函数已被调用
【发布时间】:2010-12-19 17:10:54
【问题描述】:

我正在使用 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 unit-testing mocking


    【解决方案1】:

    就您可以在运行时更改行为而言,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;
    }
    

    注意:您应该知道,此测试会修改全局函数,如果失败,可能并不总是会恢复它。
    你可能最好选择JsMock
    但是为了使用它,您需要将函数分离并将它们放入对象中,因此您根本不会有任何全局数据

    【讨论】:

    • 很好的答案。我相信有一些 JavaScript 面向方面的编程 (AOP) 库可以帮助做到这一点。
    猜你喜欢
    • 2013-04-11
    • 2021-08-21
    • 2018-01-07
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2016-08-07
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多