【问题标题】:how to write unit test for a factory method in angularJS如何在angularJS中为工厂方法编写单元测试
【发布时间】:2017-05-23 15:31:22
【问题描述】:

我有一个如下所示的工厂方法:

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 + jasmine 进行测试,到目前为止,我写了这样的东西,但失败了。

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

关于如何进行这样的测试的任何提示?

【问题讨论】:

    标签: angularjs unit-testing karma-jasmine factory


    【解决方案1】:
    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();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-18
      • 2017-10-07
      相关资源
      最近更新 更多