How to test an Angular controller with a function that makes an AJAX call without mocking the AJAX call?

安稳与你 提交于 2019-12-05 19:33:21

You just inject your own Service and Spy on the function you're calling.

describe( 'Controller: myCtrl', function () {

  var myService,
      ...;

  beforeEach( inject( function ( _myService_ ) {
    ...
    myService = _myService_;
    ...
  } ) );

  it( 'should call myService.call', inject(function ($q)
  {
    var deferred = $q.defer();
    spyOn( myService, 'call' ).andReturn(deferred.promise);
    // .and.returnValue() for jasmine 2.0
    $scope.myControllerFn();
    deferred.resolve( {} ); // for success 
    // deferred.reject() --> for error
    $scope.digest(); // do this if you want success/error to be executed.
    expect( myService.call ).toHaveBeenCalled();
  } );
} );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!