2015-06-21 28 views
0

我目前在我的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... 
    }); 
}); 

我已经发现,它并没有真正的问题是我注入的决心功能。如果我注入$location并记录它,它是一样的:它在我的浏览器中工作,但在我作为测试运行时未定义。

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

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

回答

0

我想这是其中一个“我需要离开它一个小时并回到它”的情况。事实证明,如果我手动调用解析函数,我必须自己注入会话服务。

所以不是

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

我需要在会议

route.routes['/projects'].resolve.beforeAction(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... 
    }); 
});