2013-11-03 31 views
3

我正在使用Karma + Mocha來測試具有異步調用的AngularJS服務。我將如何去告訴測試我已完成異步調用 - 即標準的Mocha done()函數在哪裏去?與Karma和Mocha的異步測試

var should = chai.should(); 
describe('Services', function() { 
    beforeEach(angular.mock.module('myApp')); 
    describe('sampleService', function(){ 
    it.only('should return some info', angular.mock.inject(function(sampleService) { 
     sampleService.get(function(data) { 
     data.should.equal('foo'); 
     //done() 
     }); 
    })); 
    }); 
}); 

回答

3

呃......我知道。

var should = chai.should(); 
describe('Services', function() { 
    beforeEach(angular.mock.module('myApp')); 
    describe('sampleService', function(){ 
    it.only('should return some info', function(done) { 
     angular.mock.inject(function(sampleService) { 
     sampleService.get(function(data) { 
      data.should.equal('foo'); 
      done(); 
     }); 
     }); 
    }); 
    }); 
}); 
1

這裏是我發現有用的模式;注入在測試之前完成,並且與承諾一起工作。在我的情況下,我使用它來驗證我的攔截器對http響應(來自LoginService所做的調用)的處理。

var LoginService, mockBackend; 

beforeEach(function() { 
    module('main.services'); 

    inject(function(_LoginService_, $httpBackend) { 
    LoginService = _LoginService_; 
    mockBackend = $httpBackend; 
    }); 
}); 

describe('login', function() { 
    it(' auth tests', function(done) { 

    var url = '/login'; 

    mockBackend.expectPOST(url) 
    .respond({token: 'a.b.c'}); 

    LoginService.login('username', 'pw') 
    .then(function(res) { 
     console.log(' * did login'); 
    }) 
    .finally(done); 

    mockBackend.flush(); 
    }); 

}); 

afterEach(function() { 
    mockBackend.verifyNoOutstandingExpectation(); 
    mockBackend.verifyNoOutstandingRequest(); 
});