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
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);
});
Update final code
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);
fireEvent.change(usernameInput, { target: { value: '000' } });
expect(fakeCb).toHaveBeenCalled();
});
CodePudding user response:
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.