Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private method Unit testing with Jasmine

Tags:

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.

like image 865
arnold Avatar asked Jul 26 '13 15:07

arnold


People also ask

Can we test private methods in unit testing?

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.

Can we write test cases for private methods?

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.

Can we test private methods in JUnit?

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.

Is Jasmine a unit test?

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.


2 Answers

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

like image 85
user11937287 Avatar answered Nov 09 '22 23:11

user11937287


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.

like image 22
achan Avatar answered Nov 09 '22 22:11

achan