【问题标题】:Angular testing service which overwrites console.log (Jasmine)覆盖 console.log (Jasmine) 的 Angular 测试服务
【发布时间】:2016-07-09 03:09:59
【问题描述】:
我有一个 Angular 日志记录服务,它根据环境常量覆盖 console.log 和其他内容,简化示例:
if(!DEBUG_ENV) {
console.log = function(){};
}
所以我的问题是如何使用 Jasmine 测试 console.log 实际上被我的服务覆盖到这个空函数。我已经模拟了我的常量并注入了我的服务,但我真的不知道如何测试 console.log 是否被 Jasmine 覆盖。
【问题讨论】:
标签:
angularjs
unit-testing
jasmine
karma-jasmine
【解决方案1】:
我已经通过模拟 $window 然后在我的服务中覆盖 $window 而不是直接覆盖控制台 [whatever] 来解决这个问题,如下所示:
$provide.value('$window', {
console: {
log: function(){return 'enabled'};
}
});
然后我像这样将它注入到我的服务中:
inject(['$window', function($window) {
_window = $window;
}]);
那么在我的服务中,我可以做到以下几点:
if(!DEBUG_ENV) {
$window.console.log = function(){return 'disabled'};
}
最后,我可以通过检查注入的 $window 模拟返回“启用”或“禁用”的内容来检查一切是否按预期发生。
expect( _window.console.log() ).toEqual('disabled');