在 React onChange 中测试功能组件

Testing functional component in React onChange

我正在尝试测试功能组件。目标是评估值是否正确更改。

我只设法执行了它呈现的测试检查。但是我找不到办法把道具传给他

输入密码

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

测试:

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

更新最终代码

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();
});

render 函数中,您可以将 props 传递给组件,就像在其他任何地方传递 props 一样。

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

根据您的评论:

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);
});

在安装时,输入显示通过 props 提供给它的密码。然后在用户提供新密码后相应地调用处理程序并且输入的值也会更新。