'jest testing react input text with max character limit inside component

Got an input box inside a React functional component that has a max character limit of five characters. Is there a way to test this using jest?

  • should prevent user from typing more than 5 characters
  • should let user type in no more than 5 characters

Component:

const [nickname, setNickname] = useState("");

const setNicknameHandler = (value: string) => {
   if (value.length > 5) {
      return; 
   }
   setNickname(value);
}

return (
    <input type="text" onChange={(e) => setNicknameHandler(e.target.value)} value={nickname}  />
)

Test:

import userEvent from "@testing-library/user-event";


it("test", () => {
    const user = userEvent.setup();

  const { getByTestId } = render(<MyComponent />);

  user.type(getByTestId(/my-input/i), "chocolatemoose");

  // chocolatemoose is greater than 5 characters so user shouldn't be able to type this, not sure how to test this though

})


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source