PrimeAcademy / weekend-salary-calculator

0 stars 61 forks source link

innerText isn't supported by jsdom #9

Open matthew-black opened 3 months ago

matthew-black commented 3 months ago

Description:

I think we've avoided this issue up until now because the lecture notes use textContent, rather than innerText. I used innerText in lectures with Biscayne, and a student encountered this:

Screenshot 2024-03-30 at 12 20 57 PM

Here's my current understanding:


How to Fix:

We'll need to:

Or:

And Also, To-Dos

DoctorHowser commented 3 months ago

\binnerText\b Explanation:

\b: A word boundary, ensuring innerText is not part of a larger word (e.g., it wouldn't match myinnerTextVariable). innerText: The literal text to match. \b: Another word boundary for the same reason as the first.


const jsContent = `element.innerText = 'Hello, world!';`;

const findInnerText = /\binnerText\b/g
const replacedContent = jsContent.replace(findInnerText, 'textContent');

console.log(replacedContent);
dgilleland commented 1 month ago

@matthew-black - If you are looking for a work-around to share with others who need it in their tests, here's an idea. I had to do this for tests I've been creating as part of a course teaching JavaScript fundamentals. It was necessary to check .innerText because students were being taught how to use that property on DOM elements.

beforeAll(() => {
    Object.defineProperty(HTMLElement.prototype, 'innerText', {
        get: function() {
            return this.textContent.toString();
        },
        set: function(str) {
            this.textContent = str.toString();
        }
    })
});

The extra use of .toString() was needed for ensuring that you always get/set the value as a string. Otherwise, you might encounter strange errors from the "plumbing" of JSDOM, such as not being able to use .split() if the value is a 'number'.

Now, this does not really "fix" the problem, as other commentary around .innerText points out the whole layout concerns with that property. So this should be treated as a "workaround" that's only intended to mess with simple string content of .innerText (and it's not bullet-proof, as it assumes no nested DOM elements in the HTMLElement you would be modifying.