我正在转移到react-testing-library,并且不知道如何触发此事件并获得更改的结果。
我已经尝试使用fireEvent
函数来触发更改,然后尝试了rerender
函数,但我似乎无法让它工作。
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
。见link。
无论何时调用fireEvent
,组件都会像在普通应用程序中一样呈现。
触发change
事件是正确的,但您必须使用事件数据传递第二个参数。
这个例子有效:
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 = getByLabelTest('First')
fireEvent.change(radio, { target: { value: "second" } });
expect(radio.value).toBe('second')
});
请从react-testing-library docs尝试这个,“render”应该可以正常工作。同意@Gpx
fireEvent.change(input, { target: { value: 'your_value_goes_here' } })
expect(input.value).toBe('expected_value')