Skip to content

Instantly share code, notes, and snippets.

@GuyMograbi
Last active October 10, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GuyMograbi/7f87e83a5be0920b9e67 to your computer and use it in GitHub Desktop.
Save GuyMograbi/7f87e83a5be0920b9e67 to your computer and use it in GitHub Desktop.
a small snippet to easily mock promises
/**
*
* @description
*
* a utility function to help mock promises. Using $q for mocks in tests is a bad practice. tests should not be asyncronous.
* This mock makes a synchronous promise like mechanism.
* I found it answers at least 80% of my use-cases and reduces code significantly.
*
* Usage:
*
* `spyOn(MyService,'callApiRequest').andReturn(window.mockPromise()) // ==> will not call any of the callbacks`
*
* To call success, run `window.mockPromise(successResponse)` - set successResponse to whatever you want.
* To call error, run `window.mockPromise(null, errorResponse)` - set errorResponse to whatever you want.
*
* The use of `window` is so we won't get jshint issues.
*
*
**/
'use strict';
window.mockPromise = function(successResponse, errorResponse){
return {
then:function(success, error){
if ( !!successResponse ){
success(successResponse);
}
if (!!errorResponse ){
error(errorResponse);
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment