如何在 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});
            });
          }
        }

我想为它编写单元测试...但我真的不确定我可以从哪里开始测试它。我只真正为工厂方法编写了单元测试,这些方法比这简单得多(如简单的数学函数(

我正在使用业力+茉莉花进行测试,到目前为止,我写了这样的东西,但失败了。

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

关于如何像这样测试渗透的任何提示?

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();
    });

最新更新