2017-01-11 8 views
0

この角度/ジャスミンの例で私は約束と$timeoutのコントローラを持っています。角度/ジャスミンテストでタイムアウト時に変数をキャッチ

$timeoutの変数セットが定義されていないため、テストに失敗しました。その他の変数には$timeoutが設定されていますが、この問題はありません。

はこれだけexpectは、他の人が働き、失敗:

expect($scope.notes).toBe(notes); 

私は待つために$timeout.flush()を使用しますが、それは無視されます。任意のアイデアをどのようにこれを修正するには?

PLUNKhttp://plnkr.co/edit/Jet3KRs7baTIzk8L30JQ

angular.module("mymodule", []) 

.service('myHttp', function($http){ 
    this.call = function($q) { 
     var defer = $q.defer(); 
     $http({url:"gothere"}) 
       .then(function (response) { 
        defer.resolve(response); 
       }); 
     return defer.promise; 
    }; 
}) 

.controller('ctl', function($scope,$timeout,myHttp) { 
     $scope.read = function (id){ 
      var data = {}; 
      data.id = id; 
      myHttp.call({url:'/getRecord', data:data}) 
       .then(function(response) { 
        $scope.id = response.id; 
        $scope.name = response.nm; 
        $scope.descrip = response.dsc; 

        $timeout(function(){ 
         $scope.notes = response.nts; 
        },1000); 

       }); 
    }; 
}); 



describe('Testing a Controller that uses a Promise', function() { 
    var $scope; 
    var $q; 
    var deferred; 

    beforeEach(module('mymodule')); 

    beforeEach(inject(function($controller, _$rootScope_, _$q_, $timeout, myHttp) { 
    $scope = _$rootScope_.$new(); 
    $q = _$q_; 
    deferred = $q.defer(); 
    spyOn(myHttp, 'call').and.returnValue(deferred.promise); 

    $controller('ctl', { 
     $scope: $scope, 
     $timeout: $timeout, 
     myHttp: myHttp 
    }); 

    $scope.read(1) 
    $timeout.flush(2000); 
    })); 

    it('should resolve promise', function() { 

    var id = 1; 
    var name = "John"; 
    var descrip = "This is the description"; 
    var notes = "These are the notes"; 

    var obj = { 
     id: id, 
     nm: name, 
     dsc: descrip, 
     nts: notes 
    }; 

    deferred.resolve(obj); 
    $scope.$apply(); 
    expect($scope.id).toBe(id); 
    expect($scope.name).toBe(name); 
    expect($scope.descrip).toBe(descrip); 
    expect($scope.notes).toBe(notes); 
    }); 

}); 

答えて

0

答えは次のとおりです。$のscope.apply後に使用する$ timeout.flush()();

$scope.$apply(); 
$timeout.flush(); 
0

変数を読み取るためにタイムアウトを与える:

it("should be proper after timeout", function(){ 
     expect($scope.notes).toBe(notes); 
}, 1000) 
+0

私はplunkを更新し、タイムアウトを追加しましたが、まだ問題があります – ps0604

関連する問題