billy
billy

Reputation: 1525

Why does $route have to be included when unit testing $location only?

I wanted to write a unit test to confirm my "otherwise" logic was working correctly. This is how I expected to do it:

it('should handle unknown routes properly', inject(function($location, $rootScope) {
    $location.path('/unknown');

    $rootScope.$digest();

    expect($location.path()).toBe('/yikes');
}));

However, what I discovered is that I had to inject $route to make this test work. Keep in mind, the unit test code didn't have to use $route but apparently it needed to be instantiated to make $location work properly.

Here's a plunkr if you're interested in more details. Why does $route have to be included when unit testing $location only?

I see lots of discussion that seems to be related:

Upvotes: 2

Views: 802

Answers (1)

tdakhla
tdakhla

Reputation: 670

The reason your test doesn't work is because $route performs the redirect logic, and $route isn't instantiated directly or indirectly from your setup. $route is instantiated only if it's injected as a dependency somewhere, such as the ng-view directive. In a real Angular setup, you'll typically configure $routeProvider and define ng-view somewhere on the page. If no ng-view exists, $route really shouldn't be instantiated and perform extra logic that slows down the app. $route and ng-view are meant to be used together.

In order to get this working, you have to either

  1. Inject $route somewhere or
  2. Do a $compile on an element with ng-view. It's important that $route be instantiated before the bad location is attempted or else $route won't know to redirect to the otherwise location.

Upvotes: 3

Related Questions