用玩笑嘲笑jquery $ .ajax
问题描述:
使用玩笑,如何测试在jQuery应用程序中发出ajax请求的函数并模拟其响应?我的应用程序未在nodejs中编译,而是直接在浏览器中运行.笑话网站上的示例 https://github.com/facebook/jest/tree/master/examples/jquery 假定ajax函数是一个单独的模块,并且整个应用程序都使用webpack之类的东西进行编译.这是我的应用程序:
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);
答
使用jest.fn()模拟$ .ajax.
Mock $.ajax by using jest.fn().
$.ajax = jest.fn().mockImplementation(() => {
const fakeResponse = {
id: 1,
name: "All",
value: "Dummy Data"
};
return Promise.resolve(fakeResponse);
});