【问题标题】:reduxForm() Connected React Component Unit Test using Jest with NO EnzymereduxForm() 使用没有酶的 Jest 连接 React 组件单元测试
【发布时间】:2019-11-22 05:43:49
【问题描述】:

我很难通过 Jest 单元测试。

我有一个提供密码表单的类,包含以下内容:

// Password.jsx

...

static propTypes = {
  checkPasswordRules: PropTypes.func,
  content: PropTypes.object
};

...

validatePassword(password, allFields) {
  const { confirmPassword = '' } = allFields;

  const errors = this.props.checkPasswordRules({
    password,
    confirmPassword
  });

  return errors.password ? errors.password.friendly : undefined;
}

...

get formContent() {
  ...

  return (
    <Field
       type="password"
       component={this.formField}
       name="password"
       label={content.passwordLabel}
       error={content.errorContent}
       validate={this.validatePassword}
    />
  );
}

...

export default reduxForm({ form: 'passwordForm' })(Password);

这是我的单元测试(开玩笑):

// Password.test.js

...

it('handles validatePassword method', () => {
  const allValues = { password: 'password', confirmPassword: 'password1' };
  const labels = content.passwordStrengthRules;
  const expected = labels.confirmMatchLabel;
  const component = renderer.create(
      <Provider store={store}>
        <Password {...props} />
      </Provider>
    );
  const instance = component.getInstance();
  const result = instance.validatePassword(allValues.password, allValues);

  expect(result).toEqual(expected);
});

我遇到的问题是,当我尝试运行 Jest 测试时,我收到一条错误消息,指出 instance.validatePassword 不是控制台中的函数。

我不确定为什么会出现这种情况,因为我使用react-test-renderer 从单元测试中的component 变量中获取instance。上面的内容不是一个函数,因为它正在寻找Providerinstance,这不是我想要做的。但是,render 没有 Provider 的组件(在测试中)会引发错误,即组件必须包装在 Provider!

有谁知道我在哪里出错了......?任何帮助将不胜感激,因为我在这里处于合法的停顿状态......

提前致谢!!

【问题讨论】:

    标签: reactjs unit-testing react-redux jestjs redux-form


    【解决方案1】:

    想通了。因为,在这种情况下,instance 只找到了包装/连接的 reduxForm 组件的实例 - Provider - 我无法访问未连接组件的方法 - Password

    通过以下方式,我可以访问Password的类方法

    it('handles validatePassword method', () => {
    
      ...
    
      const component = renderer.create(
          <Provider store={store}>
            <Password {...props} />
          </Provider>
        );
    
      ...
    
      const instance = component.root.findByType(Password).instance;
      instance.validatePassword();
    });
    

    如果有人遇到同样的问题,我希望这个答案对他们有用...

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 2021-03-14
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 2020-07-15
      • 1970-01-01
      相关资源
      最近更新 更多