javascript - Jest 测试文件中的模拟文档

标签 javascript reactjs recaptcha jestjs

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

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');
};

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

我尝试添加 setupFiles在 Jest 配置中,如 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

谢谢。

最佳答案

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

关于javascript - Jest 测试文件中的模拟文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46644563/

相关文章:

javascript - 当用户点击不再显示警报时退出 JavaScript 中的 while 循环

javascript - 谷歌分析代码 : can it go before in the document?

ruby-on-rails - ROR 中的验证码实现

javascript - 触发下拉菜单的变化事件

javascript - 代码可以工作,但给出 : Expected an assignment or function call

reactjs - 传递 Prop 时,react-google-maps map 未更新,更新时标记落后一个位置

javascript - 如何在 React Hook 中创建一个新的 JSON 对象?

reactjs - 如何在另一个 asyncThunk 中调度 asyncThunk

validation - Google INVISIBLE reCaptcha + Bootstrap 4 验证器

php - Google Recaptcha 总是返回 False