我在使用 ngMocks
和其中模拟的 $log
提供程序时遇到问题。
任何时候在我的代码中使用 $log
,测试都会失败,因为 $log
的 mock 在(第 295 行)失败:
var $log = {
log: function() { $log.log.logs.push(concat([], arguments, 0)); },
warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
info: function() { $log.info.logs.push(concat([], arguments, 0)); },
error: function() { $log.error.logs.push(concat([], arguments, 0)); },
debug: function() {
if (debug) {
$log.debug.logs.push(concat([], arguments, 0));
}
}
};
因为 $log.info.logs
看起来是未定义的而不是数组。
我注意到以这种方式更改 ngMock
中的日志功能:
info: function() {
$log.info.logs = $log.info.logs || [];
$log.info.logs.push(concat([], arguments, 0));
},
让我的测试通过。
知道为什么会发生这种情况吗?我认为这不是 ngMock
中的错误,因为我没有找到任何引用资料。
最佳答案
同样的问题发生在这里。
一旦我在 $log 上添加了一个装饰器来拦截调试调用,它就开始发生了。 如果您仅在任何 Angular 组件的初始化阶段调用日志调试,就会发生这种情况。
我解决了它检查模拟实现是否到位(在 jasmine 测试中)并调用重置以创建预期的数组。
$provide.decorator('$log', function ($delegate) {
// Keep track of the original debug method, we'll need it later.
var debugFn = $delegate.debug;
/*
* Intercept the call to $log.debug() so we can add on
* our enhancement. We're going to add on a date and
* time stamp to the message that will be logged.
*/
$delegate.debug = function () {
var args = [].slice.call(arguments);
args[0] = ['Debug', ' - ', new Date().toString(), ': ', args[0]].join('');
// HACK awfull fix for angular mock implementation whithin jasmine test failing issue
if (typeof $delegate.reset === 'function' && !($delegate.debug.logs instanceof Array)) {
// if we are within the mock and did not reset yet, we call it to avoid issue
// console.log('mock log impl fix to avoid logs array not existing...');
$delegate.reset();
}
// Send on our enhanced message to the original debug method.
debugFn.apply(null, arguments);
};
return $delegate;
});
希望这有助于...
关于angularjs - $log 中的 Angular ngMocks 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706494/