2

Using React+Enzyme+Jest

Hello, I used .innerText property to get value of certain element, see line #5 of my code:

_modifyProfileField (event) {
    const { currentAgentProfile, agentsDatabase } = this.state;
    const eventTarget = event.target;
    const agentToMod = currentAgentProfile;
    const valueToSave = event.target.innerHTML !=='<br>'
        ? eventTarget.innerText
        : '';

    if (agentToMod[eventTarget.id] !== valueToSave) {
        const style = eventTarget.id === 'name'
            ? Styles.nameSaving
            : Styles.saving;

        eventTarget.classList.add(style);
        const hideSaver = setTimeout(() => {
            eventTarget.classList.remove(style);
            clearTimeout(hideSaver);
        }, 300);

        agentToMod[eventTarget.id] = valueToSave;

        const newData = agentsDatabase.map((agent) => {
            return agent.id === agentToMod.id
                ? agentToMod
                : agent;
        });

        this.setState({
            agentsDatabase:      newData,
            currentAgentProfile: agentToMod
        });

        document.activeElement.blur();
        window.getSelection().removeAllRanges();
    }
}

When I try to run this method for testing in enzyme, event.target.innerHTML returns undefined. Changing innerText to innerHTML is unacceptable due to project requirements. Is it possible to make enzyme understand innerText from my code?

Here is my enzyme code:

expect(result
    .state()
    .currentAgentProfile.Country)
    .toBe(country);

for (const location of locations) {
    result.find('#Country').node.innerHTML = location.city;

    expect(result.find('#Country').text()).toBe(location.city);

    result.find('#Country').simulate('keydown', { key: 'Enter', keyCode: 13, which: 13 });

    result.find('#Country').simulate('blur');

    expect(result
        .state()
        .currentAgentProfile.Country)
        .toBe(location.city);
}

The blur() simulation triggers my method.

Dmytro Zhytomyrsky
  • 1,371
  • 2
  • 11
  • 17

1 Answers1

4

See this answer :

innerText vs textContent - getting some errors on Firefox

in short : var text = elem.textContent || elem.innerText;

so you could do something like this :

const valueToSave = event.target.innerHTML !=='<br>'
        ? eventTarget.innerText || eventTarget.textContent
        : '';
Community
  • 1
  • 1
Patrick
  • 3,289
  • 2
  • 18
  • 31