Created
February 9, 2014 11:12
-
-
Save BelfordZ/8897712 to your computer and use it in GitHub Desktop.
mock async function with jasmine
This file contains hidden or 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
###* | |
* Mocks an asynchronous function that calls a callback on completion. It will setup a spy for you and call | |
* the callback immediately with the parameters provided (err and res). | |
* @param {Object} scope scope of the method to mock. Ex: fs = require("fs") | |
* @param {String} method name of the method to mock. Ex: "readFile" | |
* @param {Object} err first (error) parameter you want passed to the callback of the mocked function. | |
* Ex: to test the callback handler for the case where readFile has an error | |
* mockCb(fs, "readFile", new Error("readFile Error Test"), null) | |
* @param {Object} result second (result) parameter you want passed to the callback of the mocked function | |
* Ex: to test the callback handler for the case where readFile works as expected | |
* mockCb(fs, "readFile", null, encodedData). | |
* | |
* @note the use of Object in the parameter types can be literally any object (String, Array, etc) | |
### | |
mockCb = (scope, method, error, result) -> | |
errorOutputPrefix = "Jasmine Helper: function MockCb() ->" | |
if typeof scope[method] != "function" | |
throw new Error("#{errorOutputPrefix} #{scope}.#{method} is not a function") | |
spyOn(scope, method).andCallFake( -> | |
cb = arguments[arguments.length-1] | |
if typeof cb != "function" | |
throw new Error("#{errorOutputPrefix} The callback called by #{method} is not a function") | |
setImmediate(cb, error, result) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment