Home > database >  Crash in Test React Jest when testing an input with onFocus to change an attibute
Crash in Test React Jest when testing an input with onFocus to change an attibute

Time:11-30

My Component have a field like this:

         <Form.Label>E-mail</Form.Label>
            <Form.Control
              data-testid="inputemail"
              type="email"
              onFocus={() => setAttribute(false)}
              readOnly={attribute}
              placeholder="Enter e-mail"
            />
          </Form.Group>

And I tried to pass this test:

        it("should change 'Email' input value", async () => {
          render(<LoginPage />);
          const textVariable = ""; 
          const inputemail = screen.getByTestId("inputemail");

          inputemail.focus();
          fireEvent.input(inputemail, { target: { value: textVariable } });
          expect(inputemail).toHaveFocus(); //passing now

          await waitFor(() => {
            expect(inputemail.innerHTML).toBe(textVariable);
          });
        });

Test passed ok, but I get this warning:

enter image description here

What can I do? What is the issue, I don't understand.

CodePudding user response:

The act error is saying that you are trying to access the component when it is not in stable state. Your onFocus is changing internal state of the component so the test needs to wait until it is rerendered.

Try to do the following, replace this:

inputemail.focus();
fireEvent.input(inputemail, { target: { value: textVariable } });
expect(inputemail).toHaveFocus(); //passing now

with this:

inputemail.focus();
await waitFor(() => expect(inputemail).toHaveFocus());
fireEvent.input(inputemail, { target: { value: textVariable } });

or instead of using fireEvent use the @testing-library/user-event library which should focus the field when using the type method.

await userEvent.type(inputemail, textVariable);

Just remember that user event lib API is async.

  • Related