Created
June 25, 2010 00:44
-
-
Save mmonteleone/452221 to your computer and use it in GitHub Desktop.
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
/** | |
* Mocks a function with a custom mocked handler for the duration | |
* of the execution of a context function | |
* @param {Object} parent the parent scope of the function being mocked | |
* @param {String} functionName the name of the function being mocked | |
* @param {Function} mockedFunction replacement function to use as the mocked function | |
* @param {Function} context code to execute while function is mocked | |
*/ | |
var mock = function(parent, functionName, mockedFunction, context) { | |
var nativeFunction = parent[functionName]; | |
try { | |
parent[functionName] = mockedFunction; | |
context(); | |
} finally { | |
parent[functionName] = nativeFunction; | |
} | |
}; | |
/** | |
* Usage/Examples | |
*/ | |
// Given a function and call like: | |
var sayHello = function(name){ | |
return 'Hello ' + name; | |
}; | |
var message = sayHello("John"); | |
console.log(message); | |
// You can mock it: | |
mock(window, 'sayHello', | |
// a function to use as the mock | |
function(name) { | |
return "Goodbye " + name; | |
}, | |
// wrap the code to execute while mocked | |
function(){ | |
var message = sayHello("John"); | |
// assert message = "Goodbye John" | |
}); | |
// And so, for $.ajax, you can both assert expected values from your code | |
// were passed to $.ajax as well as supply your code with fake data. | |
mock($,'ajax', | |
function(opts){ | |
// assert opts.url = 'response.html' | |
// assert opts.data had expected values | |
// then call the success property, passing fake data to calling code | |
opts.success('some fake data'); | |
}, | |
function(){ | |
// the code being tested in the context of a mocked $.ajax | |
$.ajax({ | |
url: 'response.html', | |
success: function(data) { | |
console.log('success:'); | |
console.log(data); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment