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' ...
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With