【问题标题】:Angular Unit Tests: testing a simple promise-based functionAngular Unit Tests:测试一个简单的基于 Promise 的函数
【发布时间】:2015-04-21 01:03:41
【问题描述】:

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

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

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

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

    【讨论】:

    • 谢谢,apply()ing 成功了。上面的 $timeout 被证明是不必要的,因为承诺是微不足道的。
    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2018-04-11
    • 2016-09-03
    相关资源
    最近更新 更多