这是我正在测试的玩具服务。如您所见,有三种方法method1
,method2
和method3
。这三种方法中的每一种都做同样的事情:每种方法都返回被拒绝的承诺。
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
?