【问题标题】:Async testing with Karma and Mocha使用 Karma 和 Mocha 进行异步测试
【发布时间】:2013-11-03 03:52:03
【问题描述】:

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

【问题讨论】:

    标签: javascript angularjs asynchronous mocha.js


    【解决方案1】:

    呃……我知道。

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

    【讨论】:

      【解决方案2】:

      这是我发现有用的一个模式;在测试之前完成注入,并与承诺一起工作。在我的例子中,我使用它来验证我的拦截器对 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();
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        • 2014-03-19
        • 1970-01-01
        • 1970-01-01
        • 2014-10-15
        • 1970-01-01
        • 2014-02-06
        相关资源
        最近更新 更多