【问题标题】:React-testing-library button click replacing dom elements rather than replicating themReact-testing-library 按钮单击替换 dom 元素而不是复制它们
【发布时间】: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


    【解决方案1】:

    我想知道问题是否与您的ClickElement() 函数有关。

    如果他们没有选择正确的元素怎么办。

    调试的两种方法是console.log(buttonElement) 或只是使用不同的选择器,例如CSS ID:

    const clickButton = () => {
      const buttonElement = screen.getById("YOUR_BUTTON_ID");
      fireEvent.click(buttonElement);
    };
    

    未经测试

    【讨论】:

    • 已编辑以包含点击按钮 fn。我可以得到按钮,因为 1 图像测试有效。似乎每次触发 click 事件时,它都会替换 dom 元素而不是添加它。
    猜你喜欢
    • 2020-02-05
    • 2019-03-30
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 2021-04-07
    • 2021-09-18
    • 1970-01-01
    相关资源
    最近更新 更多