【问题标题】:How to test a redux form with async validation enabled如何在启用异步验证的情况下测试 redux 表单
【发布时间】:2019-09-12 06:32:54
【问题描述】:

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

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

...
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”函数。但是由于异步验证没有通过,所以在测试的时候无法提交表单。

【问题讨论】:

    标签: reactjs jestjs enzyme redux-form


    【解决方案1】:

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

    根据我对您的代码的了解,您似乎无法通过异步验证步骤直接访问 Promise,因此您将无法直接访问 await...

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

    如果是这种情况,那么您可以将断言移至 setImmediatesetTimeout 并使用 doneJest 知道测试何时完成:

    it('should set registration info...', done => {  // <= use done
    
      // ...
    
      form.simulate('submit');
    
      setImmediate(() => {
        expect(mockOnSetRegistrationInfo).toHaveBeenCalled();  // Success!
        done();  // <= now call done
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 2013-09-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多