Unit testing Javascript anonymous functions

2019-08-12 22:40发布

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条回答
三岁会撩人
2楼-- · 2019-08-12 22:51

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;
        }
   }
查看更多
登录 后发表回答