【问题标题】:Test react-final-form change event测试 react-final-form 更改事件
【发布时间】:2019-12-02 15:31:01
【问题描述】:

谁能告诉我如何测试这个简单的行为,我已经尝试解决这个问题很长时间了,我希望我只是遗漏了一些东西,因为更改事件应该很容易测试。

我尝试调用onChange 而不是simulatewrapper.update()await new Promise(resolve => setTimeout(resolve)) 没有结果。

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');
});

这个测试惨败:

    Expected value to equal:
      "blue cheese"
    Received:
      ""

【问题讨论】:

标签: reactjs enzyme react-final-form


【解决方案1】:

我认为您可能需要在输入中添加一个 ref 并直接在其上模拟事件:

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' } } );
}

编辑:

但是,您需要确保 input.onChange 函数实际使用事件值并最终更改 input.value(可能通过 setState)。

类似问题请看这里:

Enzyme simulate an onChange event

【讨论】:

    【解决方案2】:

    我对酶了解不多。库本身使用@testing-library/react(我强烈推荐)进行测试,其中changefired with fireEvent.change()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多