3

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.

3
  • 1
    Don't ever unit tests things that are not outward facing. What you want to test sounds like testing private state. Don't test it. Commented Nov 16, 2015 at 21:16
  • Instead - just check that the counter gets incremented when whatever triggers them triggers them (that's outward facing) Commented Nov 16, 2015 at 21:17
  • just name the functions, it's not like you can't do that in any situation... Commented Nov 16, 2015 at 21:19

1 Answer 1

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;
        }
   }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.