Adi M
Adi M

Reputation: 61

MUI Password TextField value not filled with RTL

Setup: React, MUI and React Testing Library. Minimal example: a component with only a MUI TextField, type=password.

Problem: after filling the TextField with RTL, the value doesn't change. The onChange action also seems not to be triggered.

I've tried with fireEvent.change (but it threw an error), and with userEvent.type.

Component:

import React, { useState } from "react";
import TextField from "@mui/material/TextField";

export default function MuiMock() {
    const [variable, setVariable] = useState("");

    return (
        <TextField
            margin="normal"
            required            
            name="password"
            label="Password"
            type="password"
            id="password"
            data-testid="password"
            autoComplete="current-password"
            onChange={(e) => setVariable(e.target.value)}
        />
    );
}

Test:

import React from "react";
import { screen, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import MuiMock from "./Mock";

it("mock test", async () => {
    const user = userEvent.setup();
    render(
        <React.StrictMode>
            <MuiMock/>
        </React.StrictMode>
    );
    const passwordInput = screen.getByTestId("password");
    expect(passwordInput).toBeInTheDocument();  
    await user.type(passwordInput, "test12");   
    expect(screen.getByTestId("password")).toHaveValue("test12");
});

Upvotes: 0

Views: 102

Answers (2)

Adi M
Adi M

Reputation: 61

Finally got it: even though it's recommended on the web to select MUI password imputs, the screen.getByTestID method returns the entire MUI Form (div which contains label and imput). Maybe it worked in a older version.

Therefore, in order to get to the imput, I used screen.getByLabelText. Now, everything works as expected.

import React from "react";
import { screen, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import MuiMock from "./Mock";

it("mock test", async () => {
    const user = userEvent.setup();
    render(
        <React.StrictMode>
            <MuiMock/>
        </React.StrictMode>
    );

    const passwordInput = screen.getByLabelText(/password/i);
    expect(passwordInput).toBeInTheDocument();  
    //screen.debug(passwordInput);
    
    await user.type(passwordInput, "test12");
    
    expect(screen.getByLabelText(/password/i)).toHaveValue("test12");
});

Upvotes: 0

yasmine2022
yasmine2022

Reputation: 41

Could you please confirm if this problem happens consistently when the test is run, or whether it occurs occasionally? If it is intermittent, could you detail any patterns or specific scenarios that appear to be causing the issue?

Upvotes: 0

Related Questions