测试拒绝

时间:2017-04-21 09:37:06

标签: javascript angularjs promise q

这是我正在测试的玩具服务。如您所见,有三种方法method1method2method3。这三种方法中的每一种都做同样的事情:每种方法都返回被拒绝的承诺

angular.module('MyModule', []).service('MyService', ['$q', function($q) {
  this.method1 = function() {
    return $q.reject(Error('rejected1'));
  };

  this.method2 = function() {
    return new $q(function(resolve, reject) {
      reject(Error('rejected2'));
    });
  };

  this.method3 = function() {
    return $q.resolve().then(function() {
      throw Error('rejected3');
    });
  };
}]);

这是我对此服务的Jasmine测试。如您所见,有三个几乎相同的测试用例:

describe('MyModule', function() {
  var $rootScope, MyService;
  beforeEach(function() {
    angular.mock.module('MyModule');
    angular.mock.inject(function(_$rootScope_, _MyService_) {
      $rootScope = _$rootScope_;
      MyService = _MyService_;
    });
  });

  // This test passes
  it('MyService.method1 rejects', function() {
    MyService.method1().catch(function(e) {
      expect(e.message).toBe('rejected1');
    });
    $rootScope.$digest();
  });

  // This test passes
  it('MyService.method2 rejects', function() {
    MyService.method2().catch(function(e) {
      expect(e.message).toBe('rejected2');
    });
    $rootScope.$digest();
  });

  // This test fails
  it('MyService.method3 rejects', function() {
    MyService.method3().catch(function(e) {
      expect(e.message).toBe('rejected3');
    });
    $rootScope.$digest();
  });
});

其中第三项测试失败:

PhantomJS 2.1.1 (Windows 7 0.0.0): Executed 0 of 3 SUCCESS (0 secs / 0 secs)
PhantomJS 2.1.1 (Windows 7 0.0.0): Executed 1 of 3 SUCCESS (0 secs / 0.02 secs)
PhantomJS 2.1.1 (Windows 7 0.0.0): Executed 2 of 3 SUCCESS (0 secs / 0.022 secs)
PhantomJS 2.1.1 (Windows 7 0.0.0) MyModule MyService.method3 rejects FAILED
    Error: rejected3 in C:/.../src/my-module.spec.js (line 26)
    C:/.../src/my-module.spec:26:33
    processQueue@C:/.../node_modules/angular/angular.js:16698:30
    C:/.../node_modules/angular/angular.js:16714:39
    $eval@C:/.../node_modules/angular/angular.js:17996:28
    $digest@C:/.../node_modules/angular/angular.js:17810:36
    C:/.../src/my-module.spec.spec.js:62:25
PhantomJS 2.1.1 (Windows 7 0.0.0): Executed 3 of 3 (1 FAILED) (0 secs / 0.024 secs)
  • 为什么这第三种情况表现不同?
  • 我应该如何测试method3

0 个答案:

没有答案