3

我正在尝试使用react-testing-library来测试react-final-form。它适用于click-events,例如更改复选框,但我无法使用change-events。

下面是一个使用 jest 作为测试运行器的示例:

TestForm.js:

import React from 'react';
import { Form, Field } from 'react-final-form';

const TestForm = () => (
  <Form
    initialValues={{ testInput: 'initial value', testCheckbox: false }}
    onSubmit={() => null}
    render={({ values, initialValues }) => (
      <>
        {console.log('VALUES', values)}
        <label>
          Checkbox label
          <Field name="testCheckbox" component="input" type="checkbox"/>
        </label>
        <Field name="testInput" component="input" placeholder="placeholder" />
        {values.testCheckbox !== initialValues.testCheckbox && <div>Checkbox has changed</div>}
        {values.testInput !== initialValues.testInput && <div>Input has changed</div>}
      </>
    )}
  />
);

export default TestForm;

测试.js:

import React from 'react';
import { cleanup, fireEvent, render, waitForElement } from 'react-testing-library';

import TestForm from './TestForm';

afterEach(cleanup);

describe('TestForm', () => {
  it('Change checkbox', async () => {
    const { getByLabelText, getByText } = render(<TestForm />);
    const checkboxNode = getByLabelText('Checkbox label');
    fireEvent.click(checkboxNode);
    await waitForElement(() => getByText('Checkbox has changed'));
  });
  it('Change input', async () => {
    const { getByPlaceholderText, getByText } = render(<TestForm />);
    const inputNode = getByPlaceholderText('placeholder');
    fireEvent.change(inputNode, { target: { value: 'new value' } });
    await waitForElement(() => getByText('Input has changed'));
  });
});

我运行这个使用npx jest test.js并且第一个测试通过但不是第二个。

似乎不起作用的关键部分是

fireEvent.change(inputNode, { target: { value: 'new value' } });

有什么建议么?

4

0 回答 0