Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

innerText is undefined in jest test

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'   ... 
like image 233
omri_saadon Avatar asked Dec 20 '17 09:12

omri_saadon


People also ask

What is the difference between textContent and innerText?

textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows "human-readable" elements. textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of "hidden" elements.

What does innerText do in Javascript?

The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.


1 Answers

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

like image 86
Gabriel Bleu Avatar answered Sep 24 '22 08:09

Gabriel Bleu