Henrique
Henrique

Reputation: 402

Error: Unable to find an element with the text when I try a test with Jest in React

I'm news with tests, se, here is my problem

I have that simple login component:

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>
  );
}

I here my test attempty:

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 = "[email protected]";
    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)
    );
  });
});

the error that returns: Unable to find an element with the text: [email protected]. 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.

Upvotes: 10

Views: 27115

Answers (1)

skyboyer
skyboyer

Reputation: 23705

getByText looks by text content. value attribute is not text content but just one of attributes. So it will not find input by this approach.

Also it's kind of not idiomatic to search by thing you are going to assert for. Better find element by it's static properties and then check for dynamic value:

expect(getByTestId("useremail").value).toEqual("[email protected]");

PS To be more "RTL-approach" I'd also suggest to use getByPlaceholderText instead of getByTestId.

Upvotes: 11

Related Questions