如何在react-testing-library中的单选按钮上触发更改事件?

如何在react-testing-library中的单选按钮上触发更改事件?

问题描述:

我正在转移到react-testing-library,并且不知道如何触发此事件并获取更改结果.

I'm in the process of moving over to react-testing-library, and have no idea how to trigger this event and get the results of the changes.

我尝试使用fireEvent函数触发更改,然后尝试使用rerender函数,但是我似乎无法使其正常工作.

I've tried using the fireEvent function to trigger the change, and then tried the rerender function, but I can't seem to get it to work.

App.js

import React, { useState } from "react";
import logo from "./logo.svg";
import "./App.css";

const options = {
  DoTheThing: 'DoTheThing',
  DoOtherThing: 'DoOtherThing',
};

function App() {
  const [action, setAction] = useState(options.DoTheThing);

  return (
    <div className="App">
      <header className="App-header">
        <form>
          <fieldset>
            <label>
              <input
                type="radio"
                name="radio1"
                value={options.DoTheThing}
                checked={action === options.DoTheThing}
                onChange={event => setAction(event.target.value)}
              />
              First
            </label>

            <label>
              <input
                type="radio"
                name="radio1"
                value={options.DoOtherThing}
                checked={action === options.DoOtherThing}
                onChange={event => setAction(event.target.value)}
              />
              Second
            </label>
          </fieldset>
        </form>
      </header>
    </div>
  );
}

export default App;

App.test.js

import React from 'react';
import { render, cleanup, fireEvent } from 'react-testing-library';
import App from './App';

afterEach(cleanup);

it('should change the value ', () => {
  const {getByLabelText, rerender } = render(<App/>);
  const second = getByLabelText(/Second/);

  fireEvent.change(second);
  rerender(<App/>);

  expect(document.forms[0].elements.radio1.value).toEqual("DoOtherThing");

});

首先,您不必致电rerender.仅当您希望组件接收不同的道具时才使用rerender.参见链接.

First, you don't have to call rerender. You use rerender only when you want the component to receive different props. See link.

无论何时调用fireEvent,该组件都会像在常规应用程序中那样呈现.

Whenever you call fireEvent the component will render like it would in your normal app.

触发change事件是正确的,但是必须将第二个参数与事件数据一起传递.

It's correct to fire a change event, but you must pass a second parameter with the event data.

此示例有效:

import React from "react";
import { render, fireEvent } from "react-testing-library";

test("radio", () => {
  const { getByLabelText } = render(
    <form>
      <label>
         First <input type="radio" name="radio1" value="first" />
      </label>
      <label>
        Second <input type="radio" name="radio1" value="second" />
      </label>
    </form>
  );

  const radio = getByLabelText('First')
  fireEvent.change(radio, { target: { value: "second" } });
  expect(radio.value).toBe('second')
});