innerText is undefined in jest test

二次信任 提交于 2021-01-18 07:45:00

问题


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

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

'a

b

c'

and textContent is 'abc'.

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'
  ...

回答1:


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

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

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

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



来源:https://stackoverflow.com/questions/47902335/innertext-is-undefined-in-jest-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!