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.
Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.
Strictly speaking, you should not be writing unit tests that directly test private methods. What you should be testing is the public contract that the class has with other objects; you should never directly test an object's internals.
So whether you are using JUnit or SuiteRunner, you have the same four basic approaches to testing private methods: Don't test private methods. Give the methods package access. Use a nested test class.
Jasmine is one of the popular JavaScript unit testing frameworks which is capable of testing synchronous and asynchronous JavaScript code. It is used in BDD (behavior-driven development) programming which focuses more on the business value than on the technical details.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With