2017-05-23 24 views
0

我有一個工廠方法,看起來像這樣:如何編寫單元測試的工廠方法在angularJS

createApp: function(appType, subjectType, appIndicator) { 
      if (appType === 'newApp') { 
      return Restangular.all('v1/app').post({appType: appType, appIndicator: appIndicator}).then(function(app) { 
       $state.go('app.initiate.new', {appId: app.id}); 
      }); 
      } else { 
      return Restangular.all('v1/app').post({appType: appType, subjectType: subjectType, appIndicator: appIndicator}).then(function(app) { 
       $state.go('app.initiate.old', {appId: app.id}); 
      }); 
      } 
     } 

,我想爲它編寫單元測試...但我真的不知道我可以開始測試它。我真的只寫單元測試的工廠方法比這更簡單(如簡單的數學函數)

我使用karma +茉莉花進行測試,至今我寫了類似這樣的失敗。

it('should return a new application', function(done) { 
     application.createApp().then(function(app) { 
     expect(app.appType).toEqual("newApp"); 
     done(); 
     }); 
    }); 

有關如何測試這樣的osmething的任何提示?

回答

0
What you have done is wrong. You will have to mock the factory call. 

spyOn(application,'createApp').and.callFake(function() { 
    return { 
     then : function(success) { 
      success({id: "abc"}); 
     } 
    } 
}); 

it('should return a new application', function(done) { 
     spyOn($state, 'go'); 
     application.createApp(); 
     expect($state.go).toHaveBeenCalled(); 
    }); 
+0

嗯不知道這是否工作:( – jeremy