开玩笑测试中未定义innerText [英] innerText is undefined in jest test

查看:28
本文介绍了开玩笑测试中未定义innerText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 jest 进行测试时,我看到属性 innerText 未定义,而未在测试中它具有正确的值.

When testing using jest I saw that the property innerText is undefined while not in test it has the right value.

  it('get text from div', () => {
    const div = document.createElement('DIV')
    div.innerHTML = '<br>a<br>b<br>c'
    console.log('innerText', div.innerText) // undefined
    console.log('textContent', div.textContent) // 'abc'
    // expect(getTextFromDiv(div).length).toMatchSnapshot()
  })

但是当使用不在笑话测试中的相同代码时,innerText 显示:

But when using the same code not in jest test, the innerText shows :

'a

b

c'

和 textContent 是 'abc'.

and textContent is 'abc'.

为什么 jest 中的 innerText 是未定义的,而当它不是一个 jest 时,它的值是真实的?

Why innerText in jest is undefined and when it's not in a jest than the value is real?

这是它工作的代码(不是开玩笑):

This is the code where it works (not in jest):

const addTextInRichTextToPdf = (doc, text, offsetY) => {
  const div = document.createElement('DIV')
  div.innerHTML = '<br>a<br>b<br>c'
  console.log('innerText', div.innerText) // print the real value
  console.log('textContent', div.textContent) // 'abc'
  ...

推荐答案

如果你使用默认的 testEnvironment,那么你使用的是 jsdom.

If you are using the default testEnvironment, then you are using jsdom.

你可以检查这个问题,看看为什么它没有在 jsdom 中实现:https://github.com/tmpvar/jsdom/issues/1245

You can check this issue to see why it is not implemented in jsdom : https://github.com/tmpvar/jsdom/issues/1245

主要问题是innerText依靠布局引擎来指导,而jsdom没有布局引擎

The primary issue is the fact that innerText leans on the layout engine for guidance, and jsdom has no layout engine

如果您想要完整"浏览器支持,您可以查看 puppeteer

If you want "full" browser support you can check puppeteer

这篇关于开玩笑测试中未定义innerText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆