Esa Toivola
Esa Toivola

Reputation: 1538

How to test run block of a module

I want my AngularJS app to make a http request to retrieve user information from the server or redirect to login screen. I implemented this in a run block of my app's main module. But how do I test the code in a run block? Or should I move this initialization code in a controller to make it testable? I'm writing my tests with Karma and Jasmine.

Any help would be appreciated!

Upvotes: 3

Views: 3595

Answers (3)

Esa Toivola
Esa Toivola

Reputation: 1538

One solution is to move the code in the run block into a service:

angular.module('app', [])
  .run(function(runBlockService) {
    runBlockService.run();
  });

and write unit tests for that service.

Upvotes: 8

amakhrov
amakhrov

Reputation: 3939

You can get the reference to the run block via the _runBlocks property of the module.

The file with your module code:

angular.module('xmpl', []).
  run(function() {
    // some code here
  });

The test suite:

var myModule = angular.module('xmpl'),
    runBlock = myModule._runBlocks[0];
// Now can test the runBlock function according to your scenario

Upvotes: 12

UnicodeSnowman
UnicodeSnowman

Reputation: 1639

have you checked out the $routeProvider resolve property? you can use the resolve property to check on the user's logged in status and act accordingly. see http://www.youtube.com/watch?v=P6KITGRQujQ and http://docs.angularjs.org/api/ng.$routeProvider#when

in the resolve object, you can include the name of a service and/or factory that needs to be resolved (and therefore have separate unit tests for the service/factory), or if the logic is simple enough and doesn't need to be broken out in its own service, you can just write a new function

Upvotes: 2

Related Questions