Skip to content

Instantly share code, notes, and snippets.

@mmonteleone
Created June 25, 2010 00:44
Show Gist options
  • Save mmonteleone/452221 to your computer and use it in GitHub Desktop.
Save mmonteleone/452221 to your computer and use it in GitHub Desktop.
/**
* 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