2015-12-06 111 views
4

我想用摩卡,sinon和chai測試我的角應用。 特別是我感興趣的提交功能。如何爲LoginResoure創建模擬或存根以測試此功能。用sinon,mocha,chai進行角測試

謝謝!

(function() { 
'use strict'; 

class LoginController { 
    constructor($state,LoginResource) { 
     this.resource = LoginResource; 
     this.$state = $state; 
     this.credentials = {}; 
    } 
    submit() { 
     let promise = this.resource.login(this.credentials); 
     promise.then(()=>{ 
      changeState() 
     } 
    } 
    changeState() { 
     this.$state.go('home'); 
    } 
} 


angular.module('app.login').controller('LoginController', LoginController); 
})(); 



    (function() { 
'use strict'; 

class LoginResource { 
    constructor($resource, API_LOGIN) { 
     this.$resource = $resource(API_LOGIN,{'@id':id}) 
    } 

    login(data) { 
     return this.$resource.save(data).$promise; 
    } 
} 

angular.module('app.login').service('LoginResource', LoginResource); 
})(); 

編輯: 以前我在接下來的方式茉莉做到這一點:

  let deferred = $q.defer(); 
      deferred.resolve('Remote call result'); 
      mockPeopleResource = { 
       createPerson: jasmine.createSpy('createPerson').and.returnValue(deferred.promise) 
      }; 

,或者如果我想模擬@resource

mockThen = jasmine.createSpy(); 
    mockGetPeoplePromise = {then: mockThen}; 
    mockUpdate = jasmine.createSpy().and.returnValue({$promise: mockPromise}); 
    mockSave = jasmine.createSpy().and.returnValue({$promise: mockPromise}); 
    mockGetPeopleQuery = jasmine.createSpy().and.returnValue({$promise: mockGetPeoplePromise}); 
    mockResource = jasmine.createSpy().and.returnValue({ 
     get: mockGet, 
     update: mockUpdate, 
     save: mockSave, 
     query: mockGetPeopleQuery 
    }); 

回答

2

如果你想嘲笑一個服務,你可以在設置模擬值時創建測試模塊:

beforeEach(function() { 
    angular.module('test', []).factory('LoginResource', function($q) { 
    return { 
     /* You can mock an easy login function that succeed when 
     data >= 0 and fails when data < 0 */ 
     login: function(data) { 
     return $q(function(resolve, reject) { 
      if (data >= 0) return resolve(); 
      reject(); 
     }); 
     } 
    }; 
    }); 

    module('app.login', 'test'); 
}); 
+0

這太複雜了。茉莉花我做得更簡單。查看編輯 – CrueLHamsteR

相關問題