AngularJS - How to test if a function is called from within another function?

前端 未结 2 1484
南方客
南方客 2021-01-11 16:32

I\'m trying to get started with karma-jasmine and I\'m wondering why this test fails:

it(\"should call fakeFunction\", function() {
    spyOn(controller, \'a         


        
相关标签:
2条回答
  • 2021-01-11 17:14

    I just came across this problem myself. The previous answer by @Vadim has the right principles but I don't think everything was very clear. In my case, I am trying to call a public function on a service from within another function. Here are the relevant snippets:

    Service:

    angular.module('myApp').factory('myService', function() {
    
        function doSomething() {
          service.publicMethod();
        }
    
        function publicMethod(){
          // Do stuff
        }
    
        var service = {
          publicMethod: publicMethod
        };
    
        return service;
    });

    Test:

    it('calls the public method when doing something', function(){
      spyOn(service, 'publicMethod');
    
      // Run stuff to trigger doSomething()
    
      expect(service.publicMethod).toHaveBeenCalled();
    });

    The key here is that the function being tested needs to be calling the same reference as the public function that is being spy'd on.

    0 讨论(0)
  • 2021-01-11 17:20

    Your addNew method is calling fakeFunction. However, it is not calling controller.fakeFunction, which is what your expectation is.

    You'll need to change your code to use your controller, rather than these independent functions.

    EDIT: You also need to not spy on your addNew function. This is causing the function to be replaced with a spy. The other alternative is to change it to:

    spyOn(controller, 'addNew').and.callThrough()
    
    0 讨论(0)
提交回复
热议问题