Skip to content

Instantly share code, notes, and snippets.

@geraldofcneto
Forked from wilsonwc/stateMock.js
Last active December 28, 2017 12:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save geraldofcneto/7d4690dc8c81b0f1fde0 to your computer and use it in GitHub Desktop.
Save geraldofcneto/7d4690dc8c81b0f1fde0 to your computer and use it in GitHub Desktop.
angular.module('stateMock',[]);
angular.module('stateMock').service("$state", function($q){
this.expectedTransitions = [];
this.transitionTo = function(stateName, params){
if(this.expectedTransitions.length > 0){
var expectedState = this.expectedTransitions.shift();
if(expectedState.stateName !== stateName){
throw Error('Expected transition to state: ' + expectedState.stateName + ' but transitioned to ' + stateName );
}
if(expectedState.params && !angular.equals(expectedState.params, params)){
throw Error('Expected params to be ' + JSON.stringify(expectedState.params) + ' but received ' + JSON.stringify(params));
}
}else{
throw Error("No more transitions were expected! Tried to transition to "+ stateName );
}
console.log("Mock transition to: " + stateName);
return $q.when();
};
this.go = this.transitionTo;
this.expectTransitionTo = function(stateName, params){
this.expectedTransitions.push({stateName: stateName, params: params});
};
this.ensureAllTransitionsHappened = function(){
if(this.expectedTransitions.length > 0){
throw Error("Not all transitions happened!");
}
};
});
@moosehawk
Copy link

Good stuff. I'd suggest making a small change on line 10:

if (expectedState.params && !angular.equals(expectedState.params, params)) {
  throw Error('Expected params to be ' + JSON.stringify(expectedState.params) + ' but received ' + JSON.stringify(params));
}

To ensure there's an expectation of params before making the assertion.

@geraldofcneto
Copy link
Author

@moosehawk You're right. Thanks!

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