dimanche 24 janvier 2021

How to fire and test a real paste event (not simulated by calling the prop) in Jest and Enzyme

I'm trying to unit test a very simple feature in a React app where I'm blocking the user from pasting into a textarea by adding an event.preventDefault() in the event handler, like so:

function handlePaste(event) {
    event.preventDefault();
}

// ... pass it down as props

<TextareaComponent onPaste={handlePaste} />

The problem I'm having is that every method I've found of dispatching events in Jest or Enzyme just "simulates" the event by getting the function passed to the onPaste prop and calling it directly with a mock event object. That's not what I'm interested in testing.

Ideally I want to do something like this, testing that the actual value of the input hasn't changed after pasting:

const wrapper = mount(<ParentComponent inputValue="Prefilled text" />);

const input = wrapper.find(TextareaComponent);

expect(input.value).toEqual("Prefilled text")

input.doAPaste("Pasted text")

expect(input.value).not.toEqual("Pasted text")
expect(input.value).toEqual("Prefilled text")

But haven't been able to find a method that works. Any help would be appreciated!

Aucun commentaire:

Enregistrer un commentaire