Unit testing Javascript anonymous functions

不打扰是莪最后的温柔 提交于 2020-01-05 08:57:21

问题


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.


回答1:


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.

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


来源:https://stackoverflow.com/questions/33744766/unit-testing-javascript-anonymous-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!