繁体   English   中英

使用Karma和Mocha进行异步测试

[英]Async testing with Karma and Mocha

我使用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()
      });
    }));
  });
});

呃......我知道。

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

这是我发现有用的模式; 在测试之前完成注入,并且使用promises ..在我的情况下,我使用它来验证我的拦截器对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();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM