【问题标题】:Mocking jQuery $() and $ functions in jest开玩笑地模拟 jQuery $() 和 $ 函数
【发布时间】:2021-02-07 08:41:12
【问题描述】:

我对使用$.get() 的 ES6 类中的函数进行了一组测试。我能够模拟$.get()。我正在测试同一类中使用$.get()$(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
  });
});

基于 jest 文档中的 this section,我尝试使用 jest.mock 的 2 参数版本为 jQuery 构造函数添加模拟:

// 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()
  });
});

但是,添加这个打破了对 $.get() 的嘲笑,我开始收到这个错误:

TypeError: cannot read property 'mockClear' of undefined
  jQuery.get.mockClear()
             ^

基于this article,我认为我正在努力的是同时在$ 命名空间和$.fn 命名空间中模拟函数的正确方法。

This question 谈论如何模拟 $.ajax,我会做类似的事情来模拟 $.get,但我不确定它是否也能帮助我模拟 $(...).find()

有没有一种方法可以干净地模拟我需要的两个函数?

(作为旁注,我不确定如何用玩笑创建一个最小可重现的示例,但如果有人能指出一种方法,我会做一个 MRE)

【问题讨论】:

  • 现在人们似乎都在模拟 jQuery。

标签: jquery jestjs


【解决方案1】:

为了将来参考,我可以通过修改this question 上已接受答案的“Mock jQuery global”部分中的技术来解决此问题。我生成的模拟代码如下所示:

//__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;

据我了解,这本质上是该答案中提供的代码的 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()
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2020-03-05
    • 1970-01-01
    • 2019-11-17
    • 2021-11-20
    相关资源
    最近更新 更多