解决Jasmine测试中不可用的依赖项

时间:2015-06-21 01:25:14

标签: angularjs jasmine url-routing karma-jasmine

我目前正在Angular应用中的一条路线上设置一个resolve属性。我正在使用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并记录它,它就是相同的spiel:它在我的浏览器中有效,但在我作为测试运行它时是未定义的。

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

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

1 个答案:

答案 0 :(得分:0)

我想这就是其中之一&#34;我需要离开它一小时然后再回到它上面#34;的情况。事实证明,如果我手动调用resolve函数,我必须自己注入Session服务。

所以而不是

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

我需要传递会话

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...
  });
});
相关问题