Using jest how can I test a function that makes an ajax request in my jQuery app and mock its response? My app is not compiled in nodejs and runs straight in a browser. The example on the jest site https://github.com/facebook/jest/tree/master/examples/jquery assumes ajax function is a separate module and the whole app gets compiled with something like webpack. Here is my app:
(function(root) {
"use strict";
// if environment is node then import jquery.
var $ = (typeof module === "object" && module.exports) ? require('jquery') : jQuery;
function displayUser() {
var fetchCurrentUser = function (url) {
var xhr = $.get(url);
$.when(xhr)
.done(function(data) {
greet(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
};
var greet = function(data) {
$('#greet').text('Hello ' + data.name);
}
fetchCurrentUser('/my/api');
return {
fetchCurrentUser: fetchCurrentUser,
greet: greet
};
}
// Added this conditional so I can test in jest
if (typeof module === "object" && module.exports) {
// Node
module.exports = displayUser();
} else {
// Browser (root is window)
root.displayUser = displayUser();
}
})(this);
The easiest setup that I have found to test files without using modules and webpack is to manually create the scripts and to add them to
window.document
. You can reference relative paths directly inside the test file using thefs
andpath
modules. Once you have everything working you can follow ycavatars answer in order to mock the ajax calls.Here is a simple snippet testing basic jQuery functionality, you can then add new scripts to test the functions in your own file:
create a
__mocks__/jquery.js
in your project root to mock the jquery node_module. You can invoke functions in your mock jquery. Here's a simple code snippet:And add some
expect
in yourfn
to test your real logic.Mock $.ajax by using jest.fn().