【发布时间】:2021-04-28 21:27:56
【问题描述】:
最近开始为 React 组件编写测试用例,知识很少。我有一个组件,其中包含一个显示水果名称的下拉菜单和一个添加按钮。从列表中选择水果后,用户必须单击添加按钮以在底部显示该水果作为卡片(带有名称和图像)。点击添加按钮时发生了 2 件事 -
- 在底部添加了一张新卡片,显示水果和名称的图像
- 所选水果已从下拉列表中删除。
此处的示例代码 - https://codesandbox.io/s/tender-paper-2i14r?file=/src/App.js
import { useState } from "react";
import "./styles.css";
const Fruits = ["apple", "orange", "banana"];
const FruitList = ({ onChange, fruitList = [] }) => {
return (
<select onChange={onChange} aria-label="selectFruitFromList">
<option selected>Select fruit</option>
{fruitList.map((fruit) => (
<option value={fruit}>{fruit}</option>
))}
</select>
);
};
const SelectedFruit = ({ selectedFruit }) => {
return (
<ul>
{selectedFruit.map((item) => (
<li aria-label="selectedFruits">{item}</li>
))}
</ul>
);
};
export default function App() {
const [selected, setSelected] = useState();
const [fruitList, setFruitList] = useState(Fruits);
const [selectedFruit, setSelectedFruit] = useState([]);
const addFruitToTray = () => {
setSelectedFruit([...selectedFruit, selected]);
setFruitList(fruitList.filter((item) => item != selected));
setSelected("");
};
return (
<div className="App">
<h1 aria-label="hello">Hello CodeSandbox</h1>
<div>
<FruitList
onChange={(e) => setSelected(e.target.value)}
fruitList={fruitList}
/>
<button
onClick={addFruitToTray}
disabled={selected ? false : true}
aria-label="AddFruit"
>
Add
</button>
</div>
<div>
<SelectedFruit selectedFruit={selectedFruit} />
</div>
</div>
);
}
test("Select fruit and Add", ()=> {
const { debug } = render( <App/> );
await userEvent.selectOptions(screen.getByLabelText('selectFruitFromList'), 'apple' )
expect(screen.getByLabelText('AddFruit').disabled).toBeFalsy()
await userEvent.click(screen.getByLabelText('AddFruit'))
await userEvent.selectOptions(screen.getByLabelText('selectFruitFromList'), 'banana' )
await userEvent.click(screen.getByLabelText('AddFruit'))
debug()
// Test fails here
await waitFor(() => {
expect(screen.getAllByLabelText('selectedFruits')).toBeInTheDocument();
});
})
问题 -
在我上次检查 li 是否添加水果的测试中它失败了。我已经用调试检查了它,HTML 显示空的<ul> 标签(意味着没有创建<li>)。调试错误显示TestingLibraryElementError: Unable to find a label with the text of: selectedFruits
另外一点,我在 debug html 的下拉元素中看到了所有 3 项。理想情况下,它不应该是当我们单击“添加”按钮时,该项目会从下拉列表中删除。
任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: reactjs redux react-hooks react-testing-library