简体   繁体   中英

Unit Testing AngularJS Controller with $route injection

I'm trying to write a test for an Angular controller which takes $route as an injectable. Inside the controller it references this object in various places eg $route.current.params

I'm trying to work out the best way to write this test. I don't believe using the $location service to set the url will work as I need to unit test functionality inside the controller so I need the $controller service to create an instance of the controller under test.

So far all I can think of is to manually mock the $route service but this seems like a lot of work that ought to have been done before. The trouble is I can't seem to find any examples. The closest I can find is ' Injected $stateParams and $state into jasmine angular js test getting undefined ' but this isn't exactly my situation.

I can inject $route of course but it won't have any of the specific properties of the route set. What's the generally accepted way to approach this?

Unless it is ngRoute module that is tested (which is unlikely), its services should be mocked in unit tests to reduce the amount of moving parts.

$routeParams service can be recommended for its conciseness as direct replacement for $route.current.params , with few exceptions mentioned in the manual :

Note that the $routeParams are only updated after a route change completes successfully. This means that you cannot rely on $routeParams being correct in route resolve functions. Instead you can use $route.current.params to access the new route's parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM