模拟提交最终形式的反应

时间:2020-10-21 21:00:36

标签: javascript reactjs jestjs enzyme react-final-form

我正在尝试通过提交表单来测试是否正在调用回调函数。我模拟了一个onSubmit函数,该函数被传递给react-final-form。如下面的codesandbox所示,我有一个带有onSubmit回调的简单表单。

export const MyForm = ({ onSubmit }) => (
  <Form
    onSubmit={onSubmit}
    render={({ handleSubmit }) => (
      <form onSubmit={handleSubmit} autoComplete="off">
        <Field
          label="Email"
          component={Input}
          name="email"
          type="email"
          autoComplete="off"
        />
        <button>Submit</button>
      </form>
    )}
  />
);

当我模拟按钮上的click事件时,我希望它可以调用模拟函数。


  it("should call onSubmit when the button is click", () => {
    const button = wrapper.find("button");
    expect(button.length).toBeGreaterThan(0);
    button.at(0).simulate("click");
    expect(mockSubmit).toHaveBeenCalled();
  });

任何帮助将不胜感激。

Codesandbox

2 个答案:

答案 0 :(得分:0)

您需要模拟submit才能提交表单。

对于Warning: An update to ReactFinalForm inside a test was not wrapped in act(...).,您在测试的提交处理程序中使用了promise,这将导致表单验证,提交和状态更新异步。

act()提供了有关预期组件更新的范围,当组件执行此范围之外的操作时,您会收到此警告。由于在测试中,提交处理程序是异步的,因此更新将在act()函数之外进行,并且会给您此错误。

有两种方法可以解决此问题,使提交处理程序通过jest.fn()进行同步。

const mockSubmit = jest.fn();

如果您需要保持异步状态,则需要对提交的承诺采取行动/等待。这意味着您将需要创建一个已解析的promise值,并具有一个模拟函数来对其进行解析。

  const promise = Promise.resolve();
  const mockSubmit = jest.fn(() => promise);

  beforeEach(() => {
    wrapper = mount(<MyForm onSubmit={mockSubmit} />);
  });

  it("should call onSubmit when the button is click 2", async () => {
    const button = wrapper.find("form");
    expect(button.length).toBeGreaterThan(0);
    button.at(0).simulate("submit");
    expect(mockSubmit).toHaveBeenCalled();

    await act(() => promise);
  });

答案 1 :(得分:0)

我的首选方法是使用<button type="submit">Submit</button>,然后使用fireEvent.click(getByText('Submit'))like this