问题
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