如何测试(vitest)表单的提交按钮在提交时是否被禁用

问题描述 投票:0回答:1

我有以下测试(以此为模型:https://github.com/orgs/react-hook-form/discussions/8866):

it("submission is disabled if form is still submitting", async () => {
    useParams.mockReturnValue({
      formSection: "1",
      operation: "create",
    } as QueryParams);
    const user = userEvent.setup();
    let resolve: (v: unknown) => void;

    const mockOnSubmit = vitest.fn().mockReturnValue(
      new Promise((_resolve) => {
        resolve = _resolve;
      })
    );

    render(
      <MultiStepFormBase
        {...defaultProps}
        disabled={false}
        onSubmit={mockOnSubmit}
      />
    );
    const saveAndContinueButton = screen.getByRole("button", {
      name: /Save and Continue/i,
    });
    await act(async () => {
      await user.click(saveAndContinueButton);
    });

    expect(saveAndContinueButton).toBeDisabled();

    await act(async () => {
      resolve(vitest.fn);
    });

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

禁用按钮的期望总是失败:错误:expect(element).toBeDisabled()

接收到的元素未禁用:

预先感谢您的帮助!

我希望禁用提交按钮。我尝试了不同版本的测试,例如:

forms testing submit vitest submission
1个回答
0
投票

解决方案是将禁用的断言包装在

waitFor
:

 waitFor(() => {
  expect(saveAndContinueButton).toBeDisabled();
});
© www.soinside.com 2019 - 2024. All rights reserved.