AngularJS / Karma 测试:beforeEach 未执行

AngularJS / Karma testing: beforeEach not executed

我正在为 AngularJS(完全是另一个故事)和 运行 开发一些 TDD,我的 beforeEach 调用显然没有被执行。我将其简化为以下示例。

beforeEach 中的 console.log 消息和它都出现的事实证明了这一点:

describe('userApp', function(){ 
  beforeEach( function(){ 
    console.log("in beforeEach...");
  }); 

  it('should be able to log something', function(){ 
    console.log("in it...");
  }); 
});

这行不通,事实证明 beforeEach 中的 console.log 消息未显示,并且在尝试 $log.info 时失败并抛出错误消息:TypeError: Cannot read property 'info' of undefined

describe('userApp', function(){ 
  var $log;
  beforeEach(module('userApp', function($provide) {
    console.log("in beforeEach...");
    // Output messages
    $provide.value('$log', console);
  })); 
  it('should be able to log something', function(){ 
    console.log("in it...");
    $log.info("Using $log for logging...");
  }); 
});

我正在使用 Angular 1.3.15,karma 0.12.31,jasmine 2.3.4。可能是我忽略了一些明显的东西...

编辑:Michael Radionov 的解释非常有帮助;但是,我不明白为什么这个修改后的代码仍然会抛出同样的错误。

describe('userApp', function(){ 
  console.log("starting TEST3");   <=== this prints
  var $log;
  beforeEach(function() {
    console.log("TEST3: in beforeEach...");   <=== this prints
    module('userApp', function($provide, _$log_) {
      $log = _$log_;
      console.log("TEST3: in beforeEach/module...");   <=== never executed
      // Output messages
      $provide.value('$log', console);
      $log.info("TEST3: calling $log in beforeEach...");
    })
  }); 
  it('should be able to log something', function(){ 
    console.log("TEST3: in it...");
    $log.info("TEST3: Using $log for logging...");  <=== $log undefined err
  }); 
});

此外,似乎 "module('userApp'..." 中的代码从未执行过...?

您的日志消息 console.log("in beforeEach..."); 未显示的原因是因为它实际上不在 beforeEach 中,它在传递给 module(..) 作为参数的匿名函数中被 angular-mocks 认为是一个模块。只有在注入发生时才会执行此模块,同时您会收到一条日志消息 in beforeEach...,但您的测试中没有任何注入,因此它永远不会发生。 beforeEach 无论如何都会触发,您只是没有将 console.log 放在正确的位置;它会起作用:

beforeEach(function () {

  console.log("in beforeEach...");

  module('userApp', function($provide) {
    // Output messages
    $provide.value('$log', console);
  });

});

此外,您似乎忘记了将模拟的 $log 注入到您的测试套件中,您的 $log 变量永远不会获得任何值,因此它在错误状态下保持未定义状态。

describe('userApp', function(){ 

  var $log;

  beforeEach(function () {
    console.log("in beforeEach...");

    module('userApp', function($provide) {
      // Output messages
      $provide.value('$log', console);
    });

    // getting an instance of mocked service to use in a test suite
    inject(function (_$log_) {
      $log = _$log_;
    });

  }); 

  it('should be able to log something', function(){ 
    console.log("in it...");
    $log.info("Using $log for logging...");
  }); 

});

看到那个笨蛋:http://plnkr.co/edit/EirNEthh4CXdBSDAeqOE?p=preview

文档: