forgottofly
forgottofly

Reputation: 2719

Check if a function is called from other function using karma jasmine

I'm writing unit test for an angular app . I'm able to check the functions that are defined in the scope but not able to check the functions that are not in the scope..

Example:

Controller:

     $scope.showSuccessPopup=()=> {
                $scope.showsuccess = true;
            }

    function setShowSuccess (){
        $scope.showsuccess = false;
           }

Test File:

  describe("Function implementation tests",() => {
        it("Expect function to be defined", function () {
            expect(scope.showSuccessPopup).toBeDefined(); //works well   

        });

    });

which works well.But want to know how setShowSuccess can be checked.

Note:I don't want to set setShowSuccess in the scope..

Upvotes: 0

Views: 934

Answers (2)

Estus Flask
Estus Flask

Reputation: 223114

Local functions and variables within function scope are unreachable in JS. Every function and variable that is expected to be tested should be exposed.

There's no such thing as 'security' in client-side JS. The only purpose of encapsulation is to make developer's life easier, and encapsulation fails the purpose when it interferes with testing.

Consider using _ convention for private scope methods/properties to reach them in specs:

$scope._setShowSuccess = () => {
  $scope.showsuccess = false;
}

Upvotes: 1

PeterS
PeterS

Reputation: 2964

Not sure you can do that as your function is private to the controller.

As with most unit testing, testing private methods should be done through the interfaces provided so the test for $scope.showSuccessPopup should also test the private method somehow. This keeps the interfaces clean and means that they are hopefully maintainable.

I think you need to review why the function is private and if it is, it should be tested through the public ($scope) methods only. I'm not sure the worth of checking if functions are there - I guess there is a worth to you - however unit testing is generally based around a known interface that should drive the whole component so that you reach 100% coverage.

Upvotes: 2

Related Questions