【问题标题】:AngularJS JasmineJS decorated $log object not injected correctlyAngularJS JasmineJS 装饰的 $log 对象未正确注入
【发布时间】:2014-07-23 22:53:24
【问题描述】:

我是 AngularJS 和 JasmineJS 的新手。

我已经装饰了 Angular $log 服务以通过 http 进行日志记录。我验证它在程序本身中运行良好。但是,在运行 Jasmine 单元测试时,$log 调用会产生错误。我收到如下消息:

TypeError: TypeError: $log.warn.logs 未定义 http...[snip]...angular-mocks.js(第 316 行)

对于所有不同的 $log 函数($log.error.logs、$log.info.logs 等),消息都遵循此模式。

我当前的注射器如下所示:

var $httpBackend, log;

beforeEach(inject(function ($injector, $log) {
    log = $log;

     //lots of mock http service things here
}));

我也试过这个:

beforeEach(inject(['$log', function (log) {
    $log = log;
}]));

还有这个:

beforeEach(inject(function ($injector) {
     log = $injector.get('$log');

     // mock http things here
}));

失败的测试如下所示:

it('should log error', function () {
    $httpBackend.expectPOST('the url for logging');
    var controller = createController();
    log.warn('Test warning');
    $httpBackend.flush();
});

在被测试的代码中对 $log 的所有调用都会导致相同的错误。当我将它们注释掉并删除上面的失败测试时,所有单元测试都通过了。

我应该如何正确设置单元测试?

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

    答案是 angular-mocks.js 有问题,它没有正确实例化日志数组。我下载了最新的非测试版,它仍然在做同样的事情。数组的实例化发生在他们的代码中,使用对 $log.reset() 的调用,但不知何故,他们的那部分代码没有被访问。因此,我通过手动调用 $log.reset() 解决了我的问题:

     //This works
     var $log;
     beforeEach(inject(function ($injector) {
         $log = $injector.get('$log');
         $log.reset();
    
         //continue other stuff
     }));
    
     //This also works
     var log;
     beforeEach(inject(function ($injector, $log) {
        log = $log;
        log.reset();
    
        //continue other stuff
     }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      相关资源
      最近更新 更多