角度单元测试:测试基于承诺的简单函数

时间:2015-04-20 16:56:33

标签: angularjs unit-testing jasmine

我在单元测试中创建了一个非常简单的模拟服务,用于注入我正在测试的另一个对象。

beforeEach(inject(function($q, $timeout) {
  ItemService = {
    one: function(id) {
      var deferred = $q.defer();
      $timeout(function() {
        deferred.resolve({
          id: id
        });
      }, 0);
      return deferred.promise;
    }
  };
}));

现在我想编写一个简单的单元测试,确保此服务返回正确的承诺。

describe('mock service', function() {
  it('should return a promise', function() {
    // test comes here
    ItemService.one('123').then(function(item) {
      // ... but doesn't make it here
      expect(item.id).toEqual('123');
    });
  });  
});

但是,then()内的代码永远不会被执行。

1 个答案:

答案 0 :(得分:0)

单元测试中使用的$ timeout服务是mocked $timeout service,需要刷新(就像$ httpBackend一样)。这允许测试等待10分钟的代码,而不是在测试中实际等待10分钟:

ItemService.one('123').then(function(item) {
  // ... but doesn't make it here
  expect(item.id).toEqual('123');
});
$timeout.flush(1);

我不确定这会自动解决承诺,因为承诺得到解决,范围是$ apply。所以你可能还需要

$rootScope.$apply();

当然,需要在测试中注入$ timeout和$ rootScope。