Reputation: 1712
I was coding test cases for an angular application using jasmine. But many internal methods are declared as private in the services.
Example:
App.service('productDisplay', function(){
var myPrivate = function(){
//do sth
}
this.doOfferCal = function(product, date){
//call myPrivate
//do sth too
return offer;
}
});
Using jasmine it straightforward to code test for "doOfferCal" but I want to write unit test for myPrivate too.
How can I do it?
Thanks in advance.
Upvotes: 30
Views: 44182
Reputation: 174
If you want to call your private method you just have to do it like this:
component["thePrivateMethodName"](parameters);
Where component
is your service class or component class.
Upvotes: 11
Reputation: 311
Thanks jabko87.
In addition, if you want to pass the the arguments use the below example:
const myPrivateSpy = spyOn<any>(service, 'transformNative').and.callThrough();
myPrivateSpy.call(service, {name: 'PR'});
Note: Here service is the Class, transformNative is the private method and {name: 'PR'} passing an object argument
Upvotes: 21
Reputation: 6620
To test inner functions I call the outer function that calls the inner function and then vary my input according to what the inner function requires. So, in your case you would call productDisplay
and vary your input based upon what myPrivate
needs and then verify that you have the expected output. You could also spy on myPrivate
and test things that way using .havebeencalledwith
or .andcallthrough
.
Upvotes: 2
Reputation: 9469
Achan is 100% right, but if you really need to call private method in your tests (what should be never :-) ) you can do it by:
var myPrivateSpy = spyOn(productDisplayService, "myPrivate").and.callThrough();
myPrivateSpy.call();
Upvotes: 10
Reputation: 551
Is there a specific reason you wish to test your private methods?
By testing doOfferCal()
, you're implicitly testing that myPrivate()
is doing the right thing.
Though this is for RailsConf, Sandi Metz has a very good talk on what should be tested.
Upvotes: 10