jest测试ajax,jestjs - Mocking jQuery ajax call on Jest - Stack Overflow

本文档描述了在尝试使用Jest测试JavaScript文件foo_script.js中fetchData函数的Ajax请求时遇到的问题。测试代码试图模拟Ajax调用,但原始调用始终被执行,而非模拟的方法。作者探讨了是否需要将fetchData函数转换为Promise或使用sinon库来解决此问题,并寻求解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

So I have this foo_script.js file that is loaded and used on the product.html page, at the end the script adds a DIV DOM element with data in it. The info for the DIV comes from the function "fetchData":

var fetchData = function (callback) {

$.ajax({

url: "foo_data.json",

type: "GET",

success: function success(data) {

assignDataToDiv(data);

callback();

}

});

}

I'm trying to test the foo_script.js with this index.test.js file using Jest:

it('fetchs data and changes the div', () => {

document.body.innerHTML = fs.readFileSync(path.resolve(__dirname, './basic.html'), 'utf8');

spyOn($, "ajax").mockImplementation(({ success }) => success( {

url: "https://example.api",

success: "fooBar"

}));

spyOn($, 'ajax').andCallFake( function (params) {

params.success({foo: 'bar'});

});

require('./foo_script.js');

const targetedDiv = document.querySelector('.ugly_class');

expect(targetedDiv.textContent.indexOf('Ay caramba')).toBeGreaterThan(0);

});

all works kind of fine, both the original Ajax call in the function fetchData() is always executed and never the "mocked" ajax method. Need I to change the fetchData() function to a Promise instead of a callback? or need I the sinon stuff? SpyOn() method is not an interceptor? I'm a total newbie with Jest, btw.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值