【问题标题】:Error: Unable to find an element with the text when I try a test with Jest in React错误:当我在 React 中尝试使用 Jest 进行测试时,无法找到带有文本的元素
【发布时间】:2020-04-10 12:00:33
【问题描述】:

我是测试新闻,se,这是我的问题

我有那个简单的登录组件:

import React, { useState } from "react";

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  function handleLogin(event) {
    event.preventDefault();
    console.log(email, password);
  }

  return (
    <form data-testid="login-form" onSubmit={handleLogin}>
      <input
        data-testid="useremail"
        type="email"
        placeholder="Email"
        value={email}
        onChange={event => setEmail(event.target.value)}
      />

      <input
        data-testid="userpassword"
        type="password"
        placeholder="Password"
        value={password}
        onChange={event => setPassword(event.target.value)}
      />
      <button onClick={handleLogin}>login</button>
    </form>
  );
}

我在这里尝试测试:

import React from "react";
import Login from "../pages/Login";

import { render, fireEvent } from "@testing-library/react";

describe("Login component", () => {
  it("user sent email and password", () => {
    const username = "user@gmail.com";
    const password = "123456";

    let { getByText, getByTestId } = render(<Login />);

    fireEvent.change(getByTestId("useremail"), {
      target: { value: username }
    });

    fireEvent.change(getByTestId("userpassword"), {
      target: { value: password }
    });

    fireEvent.submit(getByTestId("login-form"));

    expect(getByTestId("login-form")).toContainElement(
      getByText(username, password)
    );
  });
});

返回的错误: 无法找到包含以下文本的元素:user@gmail.com。这可能是因为文本被多个元素分解。在这种情况下,你可以为你的文本匹配器提供一个函数,让你的匹配器更加灵活。

【问题讨论】:

    标签: reactjs testing jestjs tdd react-testing-library


    【解决方案1】:

    getByText 看起来像 by text contentvalue 属性不是文本内容,而只是属性之一。所以它不会通过这种方法找到输入。

    此外,根据您要断言的内容进行搜索也不是惯用的。最好通过它的静态属性找到元素,然后检查动态值:

    expect(getByTestId("useremail").value).toEqual("user@gmail.com");
    

    PS 为了更“RTL 方法”,我还建议使用 getByPlaceholderText 而不是 getByTestId

    【讨论】:

    • 谢谢你,现在我知道我犯错的地方了,你的解决方案效果很好
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多