test react component with firebase signin

Viewed 24

I am writing a small CMS in react however I can't seem to run tests on any of my components. For example I'd like to test this component which performs a signin with Firebase email/pw.

import {useContext} from "react";
import {UserContext} from "../context/userContext";
import {useNavigate} from "react-router-dom";

import {useForm} from "react-hook-form";
import {yupResolver} from '@hookform/resolvers/yup';
import * as yup from "yup";

const schema = yup.object({
    loginEmail: yup.string().email().required(),
    loginPw: yup.string().min(8).required(),
});

export default function SignIn() {
    const {signIn} = useContext(UserContext);
    const navigate = useNavigate();

    const { register, handleSubmit, formState: {errors} } = useForm({
        resolver: yupResolver(schema)
    });

    async function onSubmit(data) {
        // console.log(data);
        try {
            const cred = await signIn(
                data.loginEmail,
                data.loginPw
            );
            navigate("/admin");
        } catch {
            alert("email and / or pw incorrect");
        }
    }

    return (
    <section>
        <form onSubmit={handleSubmit(onSubmit)}>
            <h1>Sign In</h1>
            <div>
                <label
                    htmlFor="loginEmail"
                >Email</label>
                <input
                    id="loginEmail"
                    type="email"
                    {...register("loginEmail")}
                />
                <p>{errors.loginEmail?.message}</p>
            </div>
            <label
                htmlFor="loginPw"
            >Password</label>
            <input
                id="loginPw"
                type="password"
                {...register("loginPw")}
            />
            <p>{errors.loginPw?.message}</p>
            <button type="submit">Submit</button>
        </form>
    </section>
    );
}

This is my test:

import {render, screen} from "@testing-library/react";
import user from "@testing-library/user-event";
import SignIn from "./SignIn";
import {UserContextProvider} from "../context/userContext";
import { act } from 'react-dom/test-utils';
import {BrowserRouter} from "react-router-dom";


test("sign in", () => {
  act(() => {
    render (
        <BrowserRouter>
          <UserContextProvider>
              <SignIn />
          </UserContextProvider>
        </BrowserRouter>
    );
  })
  const email = screen.getByRole('textbox', {
    name: /email/i
  });
  
  user.type(email, "daniel@myemail.me");
  
});

No matter what I try - I always get the same error: TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name /email/i

Any idea what I am doing wrong?

0 Answers
Related