2017-05-23 141 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