0

I have a service that I am trying to unit test however I can't get to the functions in the service which are supposed to be private only to that module. In order to test it and put spies on it I have to expose that function to other modules. I feel this defeats the purpose of encapsulation and is a coding no-no.

These four functions, for example, are helper functions and are NOT used by any other module other than the one it is in. There is absolutely no point in putting it in the 'vm' object which is instantiated as 'this' for convention. This exposes it to other modules to use. I do not want this. However, if I don't my tests fail because my jasmine tests can't access them. :

enter image description here

So is the solution to expose all the functions I want to test to all of my other modules so they can be unit tested or is there a way I can access these variables from my tests without exposing them to everything.

1 Answer 1

1

As you said, private functions should not be directly tested during unit tests.

If they are private in that service, it means that they are called inside the same service.

So the place where to test them, is when you test the exposed functions which call them. They will perform operations on the service, return value, whatever, so you should simply test the "main exposed method" and in that describe block you test also that the private functions behave correctly.

And as you said, nope the solution is not to expose all. In the services, factories or controllers. Wherever.

And this is not only related to JS, and/or Angular, this is a standard practice in unit testing.

A brief example.

Let's suppose you have a function in the service which is exposed, called function1. Inside this method you call another function which is private, called function2 which is responsible for setting a property of the service (let's suppose it increases a counter exposed by the service).

So the place where to test function2 is inside function1. In your describe block related to function1, you add another block related to function2, and you add a test to see if the counter property has been increased after calling function1.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah okay gotcha, I misunderstood unit testing then. I thought it was testing each individual function separatly as a 'unit'
Unit means that tests should be atomic, so each test should cover a single aspect. So if you have a function which sets a value, and call another external function for example, you should implement two different tests

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.