mardi 17 décembre 2019

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

the error that returns: Unable to find an element with the text: user@gmail.com. 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.

Aucun commentaire:

Enregistrer un commentaire