Dmi*_*try 6 ajax jquery jestjs
使用 jest 如何测试在我的 jQuery 应用程序中发出 ajax 请求并模拟其响应的函数?我的应用程序不是在 nodejs 中编译的,而是直接在浏览器中运行的。jest 站点https://github.com/facebook/jest/tree/master/examples/jquery上的示例假定 ajax 函数是一个单独的模块,并且整个应用程序都是用 webpack 之类的东西编译的。这是我的应用程序:
(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);
Run Code Online (Sandbox Code Playgroud)
小智 8
使用 jest.fn() 模拟 $.ajax。
$.ajax = jest.fn().mockImplementation(() => {
const fakeResponse = {
id: 1,
name: "All",
value: "Dummy Data"
};
return Promise.resolve(fakeResponse);
});
Run Code Online (Sandbox Code Playgroud)
在项目根目录中创建一个__mocks__/jquery.js来模拟 jquery node_module。您可以在模拟 jquery 中调用函数。这是一个简单的代码片段:
const $ = {
ajax(xhr) { return this },
done(fn) {
if (fn) fn();
return this;
},
fail(fn) {
if (fn) fn();
return this;
}
};
export default $;
Run Code Online (Sandbox Code Playgroud)
并expect在你的中添加一些fn来测试你的真实逻辑。