lkartono
lkartono

Reputation: 2393

Angular test ui-router custom inline controller

I'm trying to figure out a way to test one my routes that has a really custom behavior. Here is the code of the state :

$stateProvider.state('oauth', {
  url: '/oauth/callback',
  controller: function($location, $window, ENV) {
    if ($location.hash()) {
      var pairs = $location.hash().split('&');
      var pair  = pairs[0].split('=');

      if (pair[1]) {
        localStorage.accessToken = pair[1];
        $window.location.href = '/';
      } else {
        $window.location.href = ENV.account;
      }
    }
  }
});

However, all I was able to do so far is :

describe('oauth', function() {
  beforeEach(function() {
    state = 'oauth';
  });

  it('should be the /oauth/callback url', function() {
    expect($state.href(state)).toEqual('/oauth/callback');
  });
});

I didn't find anything online that handle such a test case. Ideas?

Upvotes: 1

Views: 1054

Answers (1)

hon2a
hon2a

Reputation: 7214

Use $state.get() to get the configuration of your state.

var config = $state.get('oauth');

then mock your controller's dependencies, instantiate your controller manually

var location = jasmine.createSpyObj('$location', ['hash']);
$injector.instantiate(config.controller, {}, {
    $location: location,
    // ... (provide mocks of the services required by your controller here)
});

and test any behavior you're expecting to happen

location.hash.and.returnValue('...');
expect(location.hash).toHaveBeenCalled();
expect($window.location.href).toBe('...');

Upvotes: 1

Related Questions