Angular 单元测试:测试一个简单的基于 promise 的函数

Angular Unit Tests: testing a simple promise-based function

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

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

现在我想编写一个简单的单元测试来确保此服务 returns 是正确的承诺。

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() 中的代码永远不会执行。

单元测试中使用的 $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);

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

$rootScope.$apply();

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