2015-10-08 73 views
0

我有以下的工廠,我想測試:因緣模擬承諾響應

angular 
    .module('enigma.authFactory', [])  
    .factory('authFactory', authFactory); 

authFactory.$inject = ['$http']; 

function authFactory($http){ 
    function doesUserExist(email){ 
     return $http.post('/doesUserExist', email) 
      .success(function(data){ 
       if(data !== 'user exists'){ 
        return false; 
       } else { 
        return true; 
       } 
      }); 
    } 
} 

所以我寫了下面的測試:

describe('Auth Service Tests', function() { 
    var $httpBackend, defer, doesUserExistReqHandler; 

    beforeEach(inject(function(_$httpBackend_, $injector, $q) { 
     $httpBackend = _$httpBackend_; 
     defer = $q.defer(); 
     doesUserExistReqHandler = $httpBackend.when('POST', '/doesUserExist').respond(defer.promise); 
    })); 

    describe('authFactory.doesUserExist()', function() { 
     it('should return true is a user exists', function() { 
      user = { 
       email: '[email protected]' 
      }; 
      $httpBackend.whenPOST('/doesUserExist', user).respond('user exists'); 
      var doesUserExist = authFactory.doesUserExist(user); 
      $httpBackend.flush(); 
      expect(doesUserExist).toEqual(true); 
     }); 
    }); 
}); 

我的authFactory.doesUserExist函數內部檢查,我正確地將數據集設置爲'用戶存在',它將路由該函數返回true。但是在單元測試中,authFactory.doesUserExist被設置爲以下對象。

Expected Object({ $$state: Object({ status: 1, pending: undefined, value: Object({ data: Object({ $$state: Object({ status: 0 }) }), status: 200, headers: Function, config: Object({ method: 'POST', transformRequest: [ Function ], transformResponse: [ Function ], paramSerializer: Function, url: '/doesUserExist', data: Object({ email: '[email protected]' }), headers: Object({ Accept: 'application/json, text/plain, */*', Content-Type: 'application/json;charset=utf-8' }) }), statusText: '' }), processScheduled: false }), success: Function, error: Function }) to equal true. 

我想這個問題是測試未妥善解決的承諾,所以我設置資源變量之前authFactory.doesUserExist返回真。

我該如何解決這個問題?

回答

1

所以有幾件事情需要發生,讓你的代碼與你有什麼。

這裏是一個演示http://plnkr.co/edit/4GvMbPJgc0HcJcgFZ4DL?p=preview

  1. 您的服務(廠)需要返回一個對象。
  2. 您在$ http發佈後沒有返回承諾。
    • 我建議您使用$ q服務。

在測試

  1. 您需要導入模塊。
  2. 一定要注入你的服務
  3. 您應該刪除$httpBackend.when('POST', '/doesUserExist').respond(defer.promise);因爲它沒有完成任何事情,它實際上是得到它在其他$httpBackend.whenPost困惑。
  4. 您應該主張響應數據而不是承諾,因爲authFactory.doesUserExist(user)會返回承諾。

代碼:

var doesUserExist = authFactory.doesUserExist(user) 
    .then(function (data) { 
    responseData = data; 
    }); 

$httpBackend.flush(); 
expect(responseData).toEqual(true);