单元测试 Javascript 匿名函数 [英] Unit testing Javascript anonymous functions

查看:26
本文介绍了单元测试 Javascript 匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序的 $scope 函数中有一些匿名函数.这些是匿名的,因为我只需要它们在页面加载时运行一次(他们这样做).在这些匿名函数中,我将 $scope.itemSuccess 变量设置为 true 并返回;当满足某些规格时(不重要).这些匿名函数还会增加一个 $scope.counter;

I have a few anonymous functions inside of a $scope function in my application. These are anonymous because I only ever need them to run one time right when the page loads (which they do). Inside of those anonymous functions I'm setting a $scope.itemSuccess variable to true and return; when certain specifications are met (not important). These anonymous functions also increment a $scope.counter;

我不确定如何在 jasmine 单元测试中定位这些匿名函数.我需要确保他们正确执行逻辑并且他们适当地增加计数器.

I'm not sure how to target these anonymous functions inside of a jasmine unit test. I need to make sure they are performing the logic correctly and that they increment the counter appropriately.

推荐答案

首先,您需要以某种方式访问​​测试中的匿名函数,因此您必须将它们分配给变量或命名它们.

First, you need to access your anonymous functions in your tests somehow, so you have to assign them to a variable or name them.

完成此操作后,要测试它们,您有两个选择:将测试放在闭包(您的主函数)本身中,或者将代码添加到引用您要测试的函数的闭包中.

Once you do this, to test them, you have two options: put the tests in the closure (your main function) itself OR add code to the closure that references the functions you wish to test.

不幸的是,由于显而易见的原因,第一个选项不是很好,而第二个选项会使您的 API 膨胀.但正如 Philip Walton 在他的博客文章,您可以通过在 API 中显式调用您的测试,然后将它们作为构建过程的一部分删除来使用选项二.

Unfortunately, the first option isn't great for obvious reasons and the second option bloats your API. But as, Philip Walton explains excellently in his blog post, you can use option two by explicitly calling out your tests in your API and then removing them as part of your build process.

Philip 在他的博文中详细介绍了更多细节,我建议您阅读它,但这里有一个快速快照可以帮助您入门:

Philip goes into a lot more detail in his post, and I recommend you read it, but here is a quick snapshot to get you started:

   function closure(){

        // public variables here
        var publicVariable1 = 1;
        var publicVariable2 = 2;

        return {
            publicVariable1 : publicVariable1,
            publicVariable2 : publicVariable2,
            __tests__: {
                add: add,
                subtract: subtract
                }
        };

        // private methods you do not wish to expose (but must for unit testing purposes).      
        function add(a,b){
            return a + b;
        };

        function subtract(a,b){
            return a - b;
        }
   }

这篇关于单元测试 Javascript 匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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