Private method Unit testing with Jasmine

前端 未结 5 1755
情深已故
情深已故 2021-02-04 01:40

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         


        
相关标签:
5条回答
  • 2021-02-04 01:44

    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.

    0 讨论(0)
  • 2021-02-04 01:47

    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.

    0 讨论(0)
  • 2021-02-04 01:54

    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();
    
    0 讨论(0)
  • 2021-02-04 02:00

    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.

    0 讨论(0)
  • 2021-02-04 02:04

    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

    0 讨论(0)
提交回复
热议问题