Skip to content

Instantly share code, notes, and snippets.

@wilsonwc
Created January 10, 2014 17:24
Show Gist options
  • Star 68 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save wilsonwc/8358542 to your computer and use it in GitHub Desktop.
Save wilsonwc/8358542 to your computer and use it in GitHub Desktop.
Angular Mock for properly resolving ui-router $state in Karma unit tests
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);
var deferred = $q.defer();
var promise = deferred.promise;
deferred.resolve();
return promise;
}
this.go = this.transitionTo;
this.expectTransitionTo = function(stateName){
this.expectedTransitions.push(stateName);
}
this.ensureAllTransitionsHappened = function(){
if(this.expectedTransitions.length > 0){
throw Error("Not all transitions happened!");
}
}
});
@morrislaptop
Copy link

I have some code which examines $state.current.name to see the current state so I have added this property to the mock - https://gist.github.com/morrislaptop/8c101b59878327d932d2

@jasperkuperus
Copy link

I simplified the promise that's returned - https://gist.github.com/jasperkuperus/e96717f1f25bb71afff8

@geraldofcneto
Copy link

I added stateParams to the transitions - https://gist.github.com/geraldofcneto/7d4690dc8c81b0f1fde0

@bmwant
Copy link

bmwant commented Apr 28, 2016

I changed four-space indentation to two-space - https://gist.github.com/bmwant/4c8e5fee7a539dba69ace42b617d79c3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment