集成测试 AngularJS + Karma + Jasmine

Integration Testing AngularJS + Karma + Jasmine

我想测试我的 angular service 我想用真实数据测试它 - a.k.a(集成测试)。我正在使用 Jasmine 和 Karma。

这是我的测试:

describe('Trending Data Service', function () {
  var value = 0, originalTimeout = 0;
  var service, Enums, $httpBackend;

  // initialize module
  beforeEach(module('waterfall'));

  // initialize services
  beforeEach(inject(function ($injector) {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    $httpBackend = $injector.get('$httpBackend');
    service = $injector.get("trendingService");
    Enums = $injector.get("Enums");
    spyOn(service, 'fetch').and.callThrough();
  }));

  it('check if dependencies are defined', function () {
    expect(service).toBeDefined();
    expect(Enums).toBeDefined();
    expect(service.categories).toBeDefined();
    expect(service.fetch).toBeDefined();
  });

  it('categories array should be defined within the service', function () {
    expect(service.categories.length).toEqual(9);
    expect(service.categories).toEqual(jasmine.any(Array));
  });

  // this test is alway fails...
  it('fetch method should return initial result', function (done) {
    var promise = service.fetch(Enums.socials.viewAll, false);

    promise.then(function (result) {
      done();
    }, function() {
      expect(1).toBe(2);
      done.fail('Error occured');
    });
  });
}

这是错误: Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

我尝试了多种解决方案,但都没有成功。

编辑:29/April/2016

var trendingService = function ($q, $http) {
   var deferred = $q.defer();
   var $this = this;
   this.fetch = function (id) {
       $http.get(url).then(function (result) {
          deferred.resolve(result);
       }).catch(function(err) {
          deferred.reject(err);
       });
       return deferred.promise;
   }
   return {
      fetch: $this.fetch;
   };
};

var Enums = {
   Roles: {
      Admin: 1,
      User: 2,
      NotRegistered: 0
   }
};

angular.module('').const('Enums', Enums);

Karma 不适用于集成测试。您对 module('waterfall') 的调用实际上是对 angular.mock.module 的引用,它模拟了所有 $https 调用。

您需要使用某种形式的端到端测试来测试真实数据。我建议 http://angular.github.io/protractor/#/.