【发布时间】:2014-09-16 16:10:16
【问题描述】:
我有一个相当简单的服务,它基本上可以捕获错误,使用特定的错误类型和错误消息增强它们并广播错误事件,以便我的应用程序的部分可以处理问题。简化版可以在here找到。
服务看起来像这样:
angular
.module('app', [])
.factory('errors', function ($rootScope) {
function broadcast (error) {
$rootScope.$broadcast('err:'+error.type, error.message, error.error);
}
return {
catch: function (type, message) {
return function (error) {
broadcast({
type: type,
message: message,
error: error
});
};
}
};
});
现在我想用 Jasmine 测试该服务是否确实广播了错误。
为此,我编写了以下测试。
describe("errors: Errors (unit testing)", function() {
"use strict";
var errors,
rootScope;
beforeEach(function(){
module('app');
inject(function (_errors_, $injector) {
errors = _errors_;
rootScope = $injector.get('$rootScope');
spyOn(rootScope, '$broadcast');
});
});
it('should broadcast error event', inject(function ($q) {
$q.reject('error')
.catch(errors.catch('type', 'message'));
expect(rootScope.$broadcast).toHaveBeenCalled();
}));
很遗憾,测试从未通过,因为从未调用过 rootScope.$broadcast。
我不确定,但我认为这与广播被封装在私有 broadcast 函数中这一事实有关。有人知道如何让测试运行吗?
【问题讨论】:
标签: angularjs unit-testing jasmine karma-jasmine