3

Could someone tell me how to test this simple behavior, I've been trying to solve this for a lot of time now, and I hope I'm just missing something because a change event should be easy to test.

I tried calling onChange instead of simulate, wrapper.update(), await new Promise(resolve => setTimeout(resolve)) no result.

import * as React from 'react';
import { Form, Field } from 'react-final-form';
import { mount } from 'enzyme';


it('change event', () => {
  const wrapper = mount(
    <Form onSubmit={jest.fn()}>
    {() => (
      <Field name="name">
      {({input}) => <input value={input.value} onChange={input.onChange} />}
      </Field>
    )}
    </Form>
  )

  expect(wrapper.find('input').prop('value')).toEqual('');
  wrapper.find('input').simulate('change', { target: { value: 'blue cheese' } } );
  expect(wrapper.find('input').prop('value')).toEqual('blue cheese');
});

This test fails miserably:

    Expected value to equal:
      "blue cheese"
    Received:
      ""
elaich
  • 939
  • 1
  • 19
  • 35
  • 1
    Why are you writing tests for a npm module that is already mature and [has 100% code coverage?](https://codecov.io/gh/final-form/react-final-form) – Renan Souza Jul 24 '19 at 13:49
  • Also, [here is a very similar test for what you're trying to achieve](https://github.com/final-form/react-final-form/blob/master/src/Field.test.js#L145) – Renan Souza Jul 24 '19 at 13:51

2 Answers2

1

I think you may need to add a ref to the input and simulate the event on it directly:

it('change event', () => {
  const wrapper = mount(
    <Form onSubmit={jest.fn()}>
    {() => (
      <Field name="name">
      {({input}) => <input ref='myinput' value={input.value} onChange={input.onChange} />}
      </Field>
    )}
    </Form>
  )
  wrapper.ref('myinput').simulate('change', { target: { value: 'blue cheese' } } );
}

EDIT:

However, you need to ensure that the input.onChange function actually uses the event value and ultimately changes the input.value (probably via setState).

See here for a similar question:

Enzyme simulate an onChange event

jsdeveloper
  • 3,945
  • 1
  • 15
  • 14
0

I don't know much about enzyme. The library itself is tested using @testing-library/react (which I highly recommend), with which a change is fired with fireEvent.change().

Erik R.
  • 7,152
  • 1
  • 29
  • 39