我对 ES6 类中使用$.get(). 我能够嘲笑$.get()。我正在测试使用$.get()and的同一个类中的另一个函数$(data, ownerDocument).find(),但我无法弄清楚如何为该函数添加模拟$().find()。
我是如何嘲笑的$.get():
const jQuery = require(path/to/jquery);
jest.mock(path/to/jquery);
describe("Description", () => {
test("Test", () => {
// multiple tests with different mocks of $.get, so clearing
jQuery.get.mockClear();
jQuery.get.mockImplementation((path) => path);
// test function that uses $.get
});
});
Run Code Online (Sandbox Code Playgroud)
根据笑话文档中的这一部分,我尝试使用 2 个参数版本为 jQuery 构造函数添加模拟jest.mock:
// jest.mock(path/to/jquery);
jest.mock(path/to/jquery, () => {
return jest.fn().mockImplementation(arg1, arg2) => {
return {
find: () => console.log('find'); // just to see if structure works
};
});
});
describe("Description", () =>
test("Test", () => {
jQuery.get.mockClear();
jQuery.get.mockImplementation((path) => path);
// test function that uses $.get() and $(...).find()
});
});
Run Code Online (Sandbox Code Playgroud)
然而,添加这个打破了嘲笑$.get(),我开始收到这个错误:
TypeError: cannot read property 'mockClear' of undefined
jQuery.get.mockClear()
^
Run Code Online (Sandbox Code Playgroud)
根据这篇文章,我相信我正在努力解决的是同时模拟$命名空间和命名空间中的函数的正确方法。$.fn
这个问题讨论了如何模拟$.ajax,我做了类似的事情来模拟$.get,但我不确定它是否$(...).find()也能帮助我模拟。
有没有一种方法可以干净地模拟我同时需要的两个功能?
(顺便说一句,我不确定如何用玩笑创建一个最小可重复的示例,但如果有人能指出我的方法,我将制作一个 MRE)
为了将来的参考,我能够通过修改此问题的已接受答案的“全局模拟 jQuery ”部分中的技术来解决此问题。我生成的模拟代码如下所示:
//__mocks__/jquery.js:
const jQ = jest.requireActual("jquery");
const get = jest.fn((path) => {
return Promise.resolve(path);
});
const when = jest.fn((prom1, prom2, prom3, prom4) => {
return Promise.resolve();
});
const jQuery = jQ;
jQuery.get = get;
jQuery.when = when;
exports.jQuery = jQuery;
Run Code Online (Sandbox Code Playgroud)
据我了解,这本质上是该答案中提供的代码的 ES6 之前版本。我使用它如下。我不必担心模拟,$().find因为模拟使用该find函数的实际实现。
// foo_ut.js
const jQuery = require("../__mocks__/jquery").jQuery;
describe("Description", () =>
test("Test", () => {
jQuery.get.mockClear();
// test function that uses $.get() and $(...).find()
});
});
Run Code Online (Sandbox Code Playgroud)