Skip to content

Instantly share code, notes, and snippets.

@auxcoder
Created January 20, 2016 14:17
Show Gist options
  • Save auxcoder/c0ceb5f6adbedd63b359 to your computer and use it in GitHub Desktop.
Save auxcoder/c0ceb5f6adbedd63b359 to your computer and use it in GitHub Desktop.
$state mock for testing ui-router state
(function() {
'use strict';
describe('controllers', function(){
var scope, vm, state, $rootScope;
// Initialize the controller and scope
beforeEach(function () {
// Load the controller's module
module('AngularApp');
module('ui.router');
module('stateMock');
// Inject in angular constructs otherwise,
// you would need to inject these into each test
inject(function (_$controller_, _$rootScope_, _$state_) {
scope = _$rootScope_.$new();
state = _$state_;
vm = _$controller_('MyController', {
$scope: scope,
state: state,
$rootScope: $rootScope
});
});
});
describe('MyController', function(){
describe('state', function() {
it('Match a $state name (welcome)', function () {
state.expectTransitionTo('welcome');
});
});
it('Should exist', function () {
expect(!!vm).toBe(true);
});
});
});
})();
(function() {
'use strict';
angular.module('stateMock',[]);
angular.module('stateMock').service("$state", function($q){
this.expectedTransitions = [];
this.transitionTo = function(stateName){
if(this.expectedTransitions.length > 0){
var expectedState = this.expectedTransitions.shift();
if(expectedState !== stateName){
throw Error("Expected transition to state: " + expectedState + " but transitioned to " + stateName );
}
}else{
throw Error("No more transitions were expected! Tried to transition to "+ stateName );
}
console.log("Mock transition to: " + stateName);
this.current.name = stateName;
var deferred = $q.defer();
var promise = deferred.promise;
deferred.resolve();
return promise;
};
this.go = this.transitionTo;
this.is = function(stateName) {
if (this.current.name === stateName){
return true;
}
return false;
};
this.expectTransitionTo = function(stateName){
this.expectedTransitions.push(stateName);
};
this.ensureAllTransitionsHappened = function(){
if(this.expectedTransitions.length > 0){
throw Error("Not all transitions happened!");
}
};
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment