我有一个装饰器(当前)使用$log.error
数据创建一个对象并将其记录到控制台。它最终将被发送到服务器。
我很难用Jasmine测试这个$提供商。
我不断收到错误
TypeError: 'undefined' is not an object (evaluating '$log.info.logs.push')
这条线
original.apply($delegate, data);
提供者:
$provide.decorator('$log', [
'$delegate',
function($delegate){
var levels = ['debug', 'info', 'warn', 'error'],
contentType = 'application/json; charset=UTF-8';
_.each(levels, function(level) {
// storing the original function
var original = $delegate[ level ];
// creating a wrapped version of each $log level function
$delegate[ level ] = _.wrap(original, function(original) {
// logger data to be sent/logged to console
var data = Array.prototype.slice.call(arguments, 1);
// call to the original function which will write to the console
original.apply($delegate, data);
var postData = { date: moment(new Date()).toISOString(), level: level, message: data[ 0 ].message, stack: data[ 0 ].stack };
console.log(postData);
});
});
// returning to $log object with the new wrapped log-level functions
return $delegate;
}
]);
茉莉花测试
describe('$log decorator', function() {
var $log;
beforeEach(module('ngMock'));
beforeEach(module('myApp'));
beforeEach(inject(function(_$log_) {
$log = _$log_;
}))
it('should contain the error', function() {
var exception = {
message: "Error Message",
stack: "Error Stack"
};
$log.error(exception);
dump($log.error)
expect($log.error).toBeDefined();
});
});
答案 0 :(得分:1)
您可以尝试通过调用
注入测试/控制器之前重置$ log$log.reset()
这将设置
log.info.logs = []
所以你不再得到错误了。此外,您的测试可能更具侵略性
expect(log.error.logs).toContain(['Error Message']);
希望它有所帮助。