4

我正在使用 Karma + Mocha 通过异步调用测试 AngularJS 服务。我将如何告诉测试我已完成异步调用 - 即标准 Mocha done() 函数在哪里?

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()
      });
    }));
  });
});
4

2 回答 2

4

呃……我知道。

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();
        });
      });
    });
  });
});
于 2013-11-03T04:05:34.673 回答
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();
});
于 2015-03-11T21:04:53.507 回答