【问题标题】:Mock document in Jest test fileJest 测试文件中的模拟文档
【发布时间】:2018-03-20 13:14:39
【问题描述】:

我在一个 react 组件中有这个方法来在 componentDidMount 时加载 Google Recaptcha API

loadCaptcha = () => {
  ((d, s, id) => {
    const element = d.getElementsByTagName(s)[0];
    const fjs = element;
    let js = element;
    if (d.getElementById(id)) {
      return;
    }
    js = d.createElement(s);
    js.id = id;
    js.src = '//google.com/recaptcha/api.js';
    fjs.parentNode.insertBefore(js, fjs);
  })(document, 'script', 'google-recaptcha');
};

我在 Jest 测试文件中模拟 document 时遇到问题,因为 d 只有 Document { location: [Getter/Setter] },为此,其他对象是 undefined

我尝试在 Jest 配置中添加 setupFiles,如 other people said in another question

"setupFiles": ["<rootDir>/__mocks__/documentMock.js"]

documentMock.js:

Object.defineProperty(document, 'currentScript', {
  value: document.createElement('script'),
});

但没有运气。有人解决了吗?

也试过这个:

beforeAll(() => {
  global.document: { //code }
})

Pd:这是错误:

TypeError: Cannot read property 'parentNode' of undefined

谢谢。

【问题讨论】:

  • 你已经很接近了,只需使用 JSDOM 而不是尝试手动模拟 dom :)

标签: javascript reactjs recaptcha jestjs


【解决方案1】:

no need to manually mock JSDOM in Jest。如果您在jest.config.js 文件中选择默认的testEnvironment,它将被自动模拟:

testEnvironment: "jest-environment-jsdom",

如果您想使用 JSDOM 中未实现的一些 DOM 功能,只需在 official docs 之后模拟它们,例如

window.matchMedia = jest.fn().mockImplementation(query => {
  return {
    matches: false,
    media: query,
    onchange: null,
    addListener: jest.fn(),
    removeListener: jest.fn(),
  };
});

【讨论】:

    【解决方案2】:

    将 setupFiles 与 jsdom 一起使用:

    __mocks__/client.js

    import { JSDOM } from "jsdom"
    const dom = new JSDOM()
    global.document = dom.window.document
    global.window = dom.window
    

    然后在你的笑话配置中:

    "setupFiles": [
      "./__mocks__/client.js"
    ],
    

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 2016-02-11
      • 2020-02-13
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多