Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Testing functional component in React onChange

I am trying to test a functional component. And the goal is to evaluate that the value change correctly.

I have only managed to carry out the test checking that it renders. But I can’t find a way to pass the props to him

InputPassword

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default function InputPassword({ password, SetPassword }: any) {
  return (
    <input
      type="password"
      placeholder="password"
      value={password ?? ''}
      onChange={(event) => SetPassword(event.target.value)}
    />
  );
}

Test:

test('Login InputPassword', () => {
  render(<InputPassword />);
  const username_input = screen.queryByPlaceholderText(/password/i);
});

>Solution :

Inside the render function you can pass props to the component just like you would pass props anywhere else.

test('Login InputPassword', () => {
  render(<InputPassword password="123" />);
  const username_input = screen.queryByPlaceholderText(/password/i);
});

Based on your comment:

test("Login InputPassword", async () => {
  const fakePass = "123";
  const fakeCb = jest.fn();
  render(<InputPassword password={fakePass} setPassword={fakeCb} />);
  const usernameInput = screen.queryByPlaceholderText(/password/i);
  expect(usernameInput).toHaveValue(fakePass);
  await userEvent.type(username_input, "changed");
  expect(usernameInput).toHaveValue("changed");
  expect(fakeCb).toHaveBeenCalledTimes(7);
});

On mount the input displays the password that is given to it via props. Then after the user provides a new password which calls the handler accordingly and the input’s value is also updated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading