用玩笑嘲笑jquery $ .ajax [英] mocking jquery $.ajax with jest

查看:66
本文介绍了用玩笑嘲笑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);
    });

这篇关于用玩笑嘲笑jquery $ .ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆