首页 > 解决方案 > 如何在使用反应测试库单击按钮后测试错误消息的出现

问题描述

您好我正在尝试使用我的反应应用程序的行为来测试

目标是在单击按钮后等待错误消息。在浏览器中它看起来像这样:

  1. 按下登录按钮之前的站点
  2. 按下带有加载指示器的按钮后的站点
  3. 有错误信息的网站

图片显示了当用户尝试登录但失败时会发生什么。首先输入凭据,然后按下按钮,然后登录按钮将其文本更改为加载消息,然后在容器中显示错误消息。错误消息的内容是“Email oder Passwort sind falsch.”。如何获得一个笑话测试以等待错误消息的出现并实际检查它是否正确:

这是我到目前为止所尝试的:

import { ROUTES } from "@company/app/features";
import {
  fireEvent,
  MockedRouter,
  render,
  screen,
  waitFor,
} from "@company/test-utils";
import { tr } from "@company/utils/i18n";
import { NextRouter } from "next/router";
import { LoginPage } from "./Login.stories";

describe("Login", () => {
  it("Loads Login and causes an error", async () => {
    const router: Partial<NextRouter> = {
      pathname: "/login",
      push: jest.fn(),
    };
    render(
      <MockedRouter router={router}>
        <LoginPage />
      </MockedRouter>
    );

    await screen.findByText(tr.LOGIN.TITLE);
    await screen.findByText(tr.LOGIN.BTN_LOGIN);

    const email = screen.getByPlaceholderText(tr.LOGIN.PLACEHOLDER_EMAIL);
    const password = screen.getByPlaceholderText(tr.LOGIN.PLACEHOLDER_PASSWORD);

    fireEvent.input(email, { target: { value: "info@abc.de" } });
    fireEvent.input(password, { target: { value: "wrong" } });

    const btn = screen.getByRole("button", { name: "Login" });
    fireEvent.click(btn);

    await waitFor(() => {
      screen.findAllByText("Email oder Passwort sind falsch.");
    });
  });
});

如您所见,我正在尝试使用waitFor函数来等待错误消息的出现。问题是,即使我将函数更改为以下内容,这也会导致每次测试都通过:

await waitFor(() => {
  screen.findAllByText("Random Random Random Random")
})

我也收到此警告:

A worker process has failed to exit gracefully and has been force exited. This is likely caused by 
tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks.

使用 --detectOpenHandles 再次运行只会删除警告。行为保持不变

我查看了反应测试库的文档,发现了这个https://testing-library.com/docs/guide-disappearance

我尝试将它应用于我的解决方案,如下所示:

await waitFor(() => {
  expect(getByText("Email oder Passwort sind falsch.")).toBeInTheDocument()
})

但是现在测试失败了,我收到了这个错误信息:

TypeError: Expected container to be an Element, a Document or a DocumentFragment but got string.

我也尝试过,没有等待,只是在 fireEvent 之后使用以下内容:

await screen.findAllByText("Email oder Passwort sind falsch.")

有了这个,我认为测试也不会通过,因为它等待的时间不够长。我收到以下错误消息:

TestingLibraryElementError: Unable to find an element with the text: Email oder Passwort sind 
falsch.. This could be because the text is broken up by multiple elements. In this case, you can 
provide a function for your text matcher to make your matcher more flexible.

在fireEvent之后我也尝试过使用它:

expect(await screen.findAllByText("Email oder Passwort sind falsch.").toBeInTheDocument()

错误消息与上面的消息相同。测试也失败了。

有没有人有类似的问题并知道解决方案?我只是希望测试等待并查看,直到找到文本。帮助将不胜感激。

标签: reactjstypescriptjestjsreact-testing-library

解决方案


推荐阅读