我正在转移到 react-testing-library 的过程中,并且无法断言文本在某些状态下会发生变化。我要测试的是“选择第二个选项”文本或节点的外观。但这只是失败了,因为节点没有改变。虽然它在浏览器中工作。
我查看了文档,但由于某种原因使用wait
orwaitForElement
对我不起作用。
应用程序.js
import React, { useState } from "react";
const options = {
First: "First",
Second: "Second"
};
function App() {
const [action, setAction] = useState(options.First);
return (
<form>
<label>
<input
type="radio"
name="radio1"
value={options.First}
checked={action === options.First}
onChange={event => setAction(event.target.value)}
/>
First
</label>
<label>
<input
type="radio"
name="radio1"
value={options.Second}
checked={action === options.Second}
onChange={event => setAction(event.target.value)}
/>
Second
</label>
{action === options.First ? (
<div>First option selected</div>
) : action === options.Second ? (
<div>Second option selected</div>
) : null}
</form>
);
}
export default App;
应用程序.test.js
import React from 'react';
import { render, cleanup, fireEvent } from 'react-testing-library';
import App from './App';
afterEach(cleanup);
it('radio button', async () => {
const {getByLabelText, getByText } = render(<App/>);
const first = getByLabelText("First");
fireEvent.change(first, { target: { value: "Second" }});
expect(first.value).toEqual("Second");
expect(getByText("Second option selected").textContent).toEqual("Second option selected") ;
});