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

查看:77
本文介绍了单元测试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;

我不确定如何在茉莉花单元测试中将这些匿名函数作为目标.我需要确保它们正确执行了逻辑,并且适当地增加了计数器.

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天全站免登陆