Source:  Twitter logo

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.

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("user@gmail.com");

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

12 users liked answer #0dislike answer #012
skyboyer profile pic
skyboyer

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).