2014-01-24 48 views
0

所以,我有兩個服務:如何在嘲笑該服務的依賴時測試angualar服務?

// The service I'm testing 
angular.module("m").service("myService", function(otherService) { ... }) 

// the service I'd like to mock while testing 
angular.module("m").service("otherService", function() { ... }) 


describe("my test", function() { 

    var myService = null; 

    beforeEach(module('m')); 
    beforeEach(inject(function($injector) { 
    /////////////////////////////////////////////////////// 
    // but I want it to get injected with 'otherService' 
    /////////////////////////////////////////////////////// 
    myService = $injector.get("myService") 
    }) 

    it ('test myService', function() { 

    }) 
}) 

我想它注入myService之前模擬出otherService我測試的myService在跟進it功能的實例。

回答

0

您應該使用$provide服務將otherService實施替換爲模擬的實施。在這裏你可以:

describe('my test', function() { 
    var myService, otherServiceMock; 

    beforeEach(function() { 
     module('m'); 

     otherServiceMock = jasmine.createSpyObj('otherService', [...]); 

     module(function($provide) { 
      // Replaces the service with a mock object 
      $provide.value('otherService', otherServiceMock); 
     }); 

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

查看$provide文檔瞭解更多信息。

0

你可以只嘲笑服務的方法問題上飛

var myService, otherService; 

beforeEach(inject(function($injector) { 
    myService = $injector.get('myService'); 
    otherService = $injector.get('otherService'); 
})); 

it('calls otherService.doOther when doSomething is called', function() { 
    spyOn(otherService, 'doOther'); 
    myService.doSomething(); 
    expect(otherService.doOther).toHaveBeenCalled(); 
}); 

隨着茉莉花間諜,比如,你可以測試結果有不同的返回值等

it('doesSomething returns true when otherService.doOther returns false', function() { 
    spyOn(otherService, 'doOther').andReturn(false); 
    expect(myService.doSomething()).toBeTruthy(); 
});