javascript 在React测试库中写入输入时更改useMemo

cqoc49vn  于 2022-12-10  发布在  Java
关注(0)|答案(3)|浏览(102)

我尝试做一个测试,在更改输入时,我必须读取useMemo并更改按钮的disabled,userEvent没有进行此更改,有人经历过此过程吗?
我将把我的部分源代码放在这里,组件和测试脚本所在的位置。

<>
  <input
    data-testid="ipt-email"
    value={form.email}
    onChange={(e) => {
      setForm({ ...form, email: e.target.value });
    }}
  />
  <button data-testid="submit-sendUser" disabled={isDisabled}>
    OK
  </button>
</>

这是我的钩子

const isDisabled = useMemo(() => {
  const { email } = form;
    
  if (!email.length) return true
  
  return false;
}, [form]);

紧接着是我的单元测试,在这里我写入输入并等待状态改变
从“@测试库/用户事件”导入用户事件;

it("Should enable button when form is valid", async () => {
  const wrapper = render(<MyComponent />);

  const getEmail = wrapper.getByTestId("ipt-name");

  await userEvent.type(getEmail, 'example@example.com');

  const getBtnSubmit = wrapper.getByTestId("submit-sendUser");

  console.log(wrapper.container.innerHTML);

  expect(getBtnSubmit).not.toBeDisabled();
});

我无法使输入更改反映在按钮挂钩中

cvxl0en2

cvxl0en21#

fireEvents和强制移动到“下一帧”的组合对我很有效

const tick = () => {
  return new Promise((resolve) => {
    setTimeout(resolve, 0);
  });
};

// async test
fireEvent.change(getEmail, {target: {value: 'example@example.com'}})
await tick();
expect(getBtnSubmit).not.toBeDisabled();
ogq8wdun

ogq8wdun2#

需要等待操作后发生更改

await waitFor(() => expect(getBtnSubmit).not.toBeDisabled())

在应用于useEffect的处理程序中移动代码,但我觉得在处理程序中处理验证更好。
希望能有所帮助

5uzkadbs

5uzkadbs3#

在常量getEmail中,您会得到一个data-testid ='ipt-name'而不是'ipt-email'的组件。
我的测试:

import { render, screen, waitFor } from '@testing-library/react';
import App from './App';
import userEvent from '@testing-library/user-event';

it("Should enable button when form is valid", async () => {
  render(<App />);

  expect(screen.getByTestId("submit-sendUser")).toBeDisabled();

  const getEmail = screen.getByTestId("ipt-email");

  userEvent.type(getEmail, 'example@example.com');

  await waitFor(() => expect(screen.getByTestId("submit-sendUser")).not.toBeDisabled());
});

我组件:

import React, { useMemo, useState } from "react";

export const App = () => {
  const [form, setForm] = useState({ email: '' });

  const isDisabled = useMemo(() => {
    const { email } = form;

    if (!email || !email.length) return true;

    return false;
  }, [form]);

  return (
    <div>
      <input
        data-testid="ipt-email"
        value={form.email}
        onChange={(e) => {
          setForm({ ...form, email: e.target.value });
        }}
      />
      <button data-testid="submit-sendUser" disabled={isDisabled}>
        OK
      </button>
    </div>
  );
};

export default App;

相关问题