【发布时间】:2021-11-06 13:41:01
【问题描述】:
我有一个简单的应用程序,它调用 API 并在点击时将图像添加到 DOM:
export const DogGallery = () => {
const [dogPhotos, setDogPhotos] = useState([]);
const getDogPhoto = async () => {
const newPhoto = await fetch(
"https://dog.ceo/api/breeds/image/random"
).then((res) => res.json());
const photosArray = [...dogPhotos, newPhoto.message];
setDogPhotos(photosArray);
};
return (
<>
<p>Dog gallery</p>
<Button handleClick={getDogPhoto} />
{dogPhotos.length > 0 &&
dogPhotos.map((photo, i) => (
<DogPhoto source={photo} key={i} number={i} />
))}
</>
);
};
但是,当我在 react-testing-library 中对此进行测试并触发五次点击时,我仍然会在 DOM 中得到一张图片。
const clickButton = () => {
const buttonElement = screen.getByText("click!");
fireEvent.click(buttonElement);
};
it("should render 5 images", async () => {
render(<DogGallery />);
clickButton();
clickButton();
clickButton();
clickButton();
clickButton();
const elements = await screen.findAllByRole("image");
expect(elements.length).toBe(5); // fails, as it only returns a length of 1
});
如何让 react-testing-library 复制/添加图像到 dom 而不是替换它们?
我对 0 张图片和 1 张图片进行了测试,它们都通过了。
您可以在此处查看完整代码:https://codesandbox.io/s/bold-bash-cwttx?file=/src/App.js
【问题讨论】:
标签: javascript reactjs unit-testing jestjs react-testing-library