在Jest测试文件中模拟文档

时间:2017-10-09 10:43:57

标签: javascript reactjs recaptcha jestjs

我在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配置中添加setupFilesother 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

感谢。

2 个答案:

答案 0 :(得分:1)

将setupFiles与jsdom一起使用:

<强> __嘲笑__ / client.js

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

然后在你的jest配置中:

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

答案 1 :(得分:1)

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

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