Reputation: 14295
I am currently setting up a resolve property on one of my routes in my Angular app. I am using ngRoute. Also, I inject a service called Session
into my resolve function.
My route looks like this:
$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);
}
}
});
In my browser, this logs Session, Object {}
to my console, as expected.
However, when I run my tests, the same line prints Session, undefined
to my console.
My test looks like this:
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...
});
});
I've already found out that it doesn't really matter what I inject into the resolve function. If I inject $location
and log that, it's the same spiel: it works in my browser, but is undefined when I run it as a test.
My tests on Jasmine and Karma. The app was generated with Yeoman.
Why are the resolve dependencies undefined in my test? Is there some additional setup my tests need?
Upvotes: 0
Views: 228
Reputation: 14295
I guess this was one of those "I need to step away from it for an hour and come back to it" situations. It turns out that I have to inject the Session service myself if I invoke the resolve function manually.
So instead of
route.routes['/projects'].resolve.beforeAction();
I need to pass in the Session
route.routes['/projects'].resolve.beforeAction(Session);
Otherwise, the Session parameter of obviously going to be undefined. To do that, I injected the Session service into my test as such:
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...
});
});
Upvotes: 0