当前位置: 首页 > 工具软件 > jQuery Spy > 使用案例 >

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

江迪
2023-12-01

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.

 类似资料: