如何在启用异步验证的情况下测试Redux表单

时间:2019-04-23 05:45:23

标签: reactjs jestjs enzyme redux-form

我为redux表单中的字段启用了异步验证。我使用玩笑和酵素来测试表单提交。

我尝试使用简单的已解决的承诺模拟异步验证功能,但仍无法提交表单。但是我删除了异步验证,可以毫无问题地提交表单。

...
jest.mock('../../../../../../utilities/validators');

it('should set registration info and set current step with correct values when registration form is successfully submitted', () => {
    const store = createStore(
      combineReducers({
        form: formReducer,
      }),
    );

    validateEmailUnique.mockImplementation(() => Promise.resolve());

    const mockOnSetRegistrationInfo = jest.fn();
    const mockOnSetRegistrationCurrentStep = jest.fn();

    const updatedProps = {
      ...defaultProps,
      onSetRegistrationInfo: mockOnSetRegistrationInfo,
      onSetRegistrationCurrentStep: mockOnSetRegistrationCurrentStep,
    };

    const wrapper = mount(
      <Provider store={store}>
        <StepOne {...updatedProps} />
      </Provider>,
    );

    const form = wrapper.find('form');
    const businessEmailTextField = wrapper.find(
      'input#business-email-text-field',
    );

    businessEmailTextField.simulate('change', {
      target: {
        value: 'business@email.com',
      },
    });

    form.simulate('submit');

    expect(mockOnSetRegistrationInfo).toHaveBeenCalled();

我希望先提交表单,然后再调用表单提交的回调函数内部的“ onSetRegistrationInfo”函数。但是,由于未通过异步验证,因此无法在测试期间提交表单。

1 个答案:

答案 0 :(得分:0)

问题在于,expect运行并失败时,异步验证尚未完成。

从我看到的代码来看,您似乎无法从异步验证步骤直接访问Promise,因此您将无法直接await

...但是,如果您模拟了任何async操作以立即解决,那么它们都应该在Promise微任务队列的一个周期中完成。

如果是这种情况,则可以将断言移至setImmediatesetTimeout之类,并使用doneJest通知测试何时完成:< / p>

it('should set registration info...', done => {  // <= use done

  // ...

  form.simulate('submit');

  setImmediate(() => {
    expect(mockOnSetRegistrationInfo).toHaveBeenCalled();  // Success!
    done();  // <= now call done
  });
});
相关问题