首页 > 解决方案 > 笑话/酶 | 测试屏蔽/取消屏蔽密码功能

问题描述

我在我的反应组件中有一个表单,它有 2 个调用函数的字段,单击时会show button屏蔽和取消屏蔽特定字段。基本上,我需要一些关于如何测试函数本身的帮助。

功能:

  togglePasswordMask = e => {
    const { type } = this.state;
    e.preventDefault();
    this.setState(prevState => ({
      passwordIsMasked: !prevState.passwordIsMasked,
      type: type === 'password' ? 'input' : 'password'
    }));
  };

我在我的渲染方法中调用该函数,如下所示:

<div className="input-group mb-3">
  <Field
        type={type}
        className={classNames('form-control', {
       'is-invalid': errors.password && touched.password
     })}
     placeholder="Password (Required)"
     name="password"
   />
   <div className="input-group-append">
   <span className="input-group-text">
   <div
    className={type === 'password' ? 
   'fa fa-eye fa-lg' : 'fa fa-eye-slash fa-lg'}
   onClick={this.togglePasswordMask}
   />
  </span>
 </div>
</div>

它还有一个 INITIAL_STATE:

  state = {
    type: 'password',
    groups: []
  };

你能帮我吗,为此使用 Jest 和 Enzyme 编写测试用例。我尝试了以下方法,但它们似乎不起作用:

  describe('UserCreateForm TogglePassword', () => {
    it('Should unmask password and confirmPassword on click', () => {
      const maskElement = wrapper.find('.fa fa-eye fa-lg');
      const maskFn = maskElement.simulate('click');
      expect(maskFn().state()).toEqual('input');
    });
  });

我得到这个错误:TypeError: Cannot read property 'preventDefault' of undefined

在找到另一个答案后,我进行了一点迭代,现在我的测试看起来像这样:

    it('Should unmask password and confirmPassword on click', () => {
      console.log(wrapper.debug());
      const maskElement = wrapper.find('.fa-eye');
      const maskFn = maskElement.simulate('click', {
        preventDefault: () => {}
      });
      expect(maskFn().state()).toEqual('input');
    });

现在,我得到另一个错误:maskFn, is not a function.

标签: javascriptreactjsunit-testingjestjsenzyme

解决方案


您的直接问题是因为根据Enzyme docsmaskElement.simulate返回,这是一个对象而不是函数。完全摆脱,调用并忽略它的返回值,然后运行你的反对。SelfmaskFnmaskElement.simulateexpectmaskElement.state()

(另外,不要针对组件的内部状态进行测试——有些人认为这是一种反模式,因为你正在测试组件实现而不是组件行为——考虑expect让组件呈现 a <Field type="password" />vs a <Field type="text" />


推荐阅读