Private method Unit testing with Jasmine

天涯浪子 提交于 2019-12-31 12:26:02

问题


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.


回答1:


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.




回答2:


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();



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/17885635/private-method-unit-testing-with-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!