Last active
October 10, 2015 14:16
-
-
Save GuyMograbi/7f87e83a5be0920b9e67 to your computer and use it in GitHub Desktop.
a small snippet to easily mock promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @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