【问题标题】:Resolve dependencies not available in Jasmine test解决 Jasmine 测试中不可用的依赖项
【发布时间】:2015-06-21 01:25:13
【问题描述】:

我目前正在我的 Angular 应用程序中的一条路线上设置解析属性。我正在使用 ngRoute。另外,我将一个名为 Session 的服务注入到我的解析函数中。

我的路线是这样的:

$routeProvider.when('/projects', {
  templateUrl: 'views/projects/index.html',
  controller: 'ProjectsCtrl',
  resolve: {
    beforeAction: function (Session) { // <-- here's the injection
      // this logs an object in the browser,
      // but in my test it logs as undefined
      console.log('Session', Session);
    }
  }
});

在我的浏览器中,这会按预期将Session, Object {} 记录到我的控制台。

但是,当我运行测试时,同一行将 Session, undefined 打印到我的控制台。

我的测试如下所示:

beforeEach(module('visibilityApp'));

var route;

describe('/projects', function () {
  beforeEach(inject(function ($route) {
    route = $route;
  }));

  it('checks if the user is logged in', function () {
    // Here I just invoke the function that's assigned to the
    // route's resolve property, but Session then seems
    // to be undefined.
    route.routes['/projects'].resolve.beforeAction();

    // then more of the test...
  });
});

我已经发现,我将什么注入到 resolve 函数中并不重要。如果我注入 $location 并记录它,它是相同的语言:它在我的浏览器中工作,但在我作为测试运行时未定义。

我对 Jasmine 和 Karma 的测试。该应用是使用 Yeoman 生成的。

为什么我的测试中未定义解析依赖项?我的测试需要一些额外的设置吗?

【问题讨论】:

    标签: angularjs jasmine url-routing karma-jasmine


    【解决方案1】:

    我想这是“我需要离开它一个小时然后回到它”的情况之一。事实证明,如果我手动调用 resolve 函数,我必须自己注入 Session 服务。

    所以不是

    route.routes['/projects'].resolve.beforeAction();
    

    我需要传入Session

    route.routes['/projects'].resolve.beforeAction(Session);
    

    否则,Session的参数显然会是未定义的。为此,我将 Session 服务注入到我的测试中:

    beforeEach(module('visibilityApp'));
    
    var route,
        Session;
    
    describe('/projects', function () {
      beforeEach(inject(function ($route, _Session_) {
        route = $route;
        Session = _Session_;
      }));
    
      it('checks if the user is logged in', function () {
        route.routes['/projects'].resolve.beforeAction(Session);
    
        // then more of the test...
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 2016-12-27
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2012-01-01
      相关资源
      最近更新 更多