2013-10-31 26 views
16

Aşağıdaki test başarısız oluyor ve nedenini anlayamıyorum? Yasemin ile ertelenmiş vaatleri nasıl test edeceğimi anlamaya çalışıyorum.Jasmine ile Açısal Sözün Test Edilmesi

Hata

Expected undefined to be 'Resolved Data'. 

Testi

describe('Queued Repository', function() { 
    var ctrl, 
     rootScope, 
     scope, 
     service; 

    beforeEach(function() { 
     module('testApp'); 

     inject(function ($rootScope, $controller, TestSrvc) { 
      rootScope = $rootScope; 
      scope = $rootScope.$new(); 
      service = TestSrvc; 
     }); 
    }); 

    afterEach(inject(function ($rootScope) { 
     $rootScope.$apply(); 
    })); 

    it('test something', function() { 
     expect(service.calculate(1, 5)).toBe(6); 
    }); 

    it('resolves promises', function() { 
     var result; 

     service.getPromise().then(function (data) { 
      result = data; 
     }); 

     rootScope.$apply(); 
     expect(result).toBe('Resolved Data'); 
    }); 
}); 

Servis

var app = angular.module('testApp', []); 

app.service('TestSrvc', ['$q', '$timeout', '$http', function ($q, $timeout, $http) { 
    return { 
     getPromise: function() { 
      var d = $q.defer(); 

      $timeout(function() { 
       d.resolve('Defered Result'); 
      }, 5000); 

      return d.promise; 
     }, 
     getSomething: function() { 
      return "Test"; 
     }, 
     calculate: function (x, y) { 
      return x + y; 
     } 
    } 
}]); 
+0

Beklemeyin (sonuç) .toEqual ('Defered Result'); '? –

+0

@JonathanPalumbo - Evet, ama hala çalışmıyor. – Sam

+2

Evet Ne demek istediğini anlıyorum, sonuç undefined'. Eğer bir söz verilmişse, $ http 'i onaylama işleminizi yapmadan önce' $ httpBackend.flush() 'i çağırmanızı öneririm. Ancak, $ q' hizmetini kullanmak başka bir hikaye. –

cevap

9

$timeout.flush() b aramayı deneyin efore expect(result).toBe('Resolved Data');.

+2

Teşekkürler TON! Hala $ rootScope'a ihtiyacım var mı? $ Apply()? – Sam

+1

"Beklenmeyen istek" alıyorum GET http: //my.test.service/someObject/someId herhangi bir istek bekleniyor – FlavorScape

+0

Bu GET aramalarının nereden geldiği, test istediğiniz dosyanın tam içeriğini göstermiyorsunuz? Servise neden "$ http" enjekte edilir? –

3

Örneğinizde, hem $timeout.flush() AND $rootScope.$apply()'u aramanız gerekecek.

Açıklama: $timeout.flush(), $timeout hizmetinizi hemen çalışmaya zorlayacaktır. Servisiniz daha sonra 'resolve' olarak adlandırılacaktır - ancak promise.then() sonraki sindirim döngüsüne kadar çağrılmayacaktır; bu nedenle, herhangi bir 'çözme' ve 'saat' yaymak için $rootScope.$apply()'u aramanız gerekecektir - bu senkronize olarak gerçekleşecektir.

Jasmine yılında

NOTE:, sizin promise.then() fonksiyon aksi takdirde promise.then() fonksiyonunu ateş olmaz $rootScope.$apply için BEFORE çağrı gösterilmesini sağlamak. (Yasemin'de bunun neden böyle olduğunu anlamadım.)

İlgili konular