如何测试默认的道具功能是否附加到组件? \|反应 \|笑话 \|酵素

新手上路,请多包涵

在这种情况下,我们如何编写测试来检查 defaultProps 函数( handleChange: () => {},handleBlur: () => {},handleSubmit: () => {} )附加到 dom 并且它们是否正常工作?

我知道当我们作为 props 传递时我们可以测试功能,但寻求帮助来测试默认功能。谢谢,

 import React from 'react';
import PropTypes from 'prop-types';

const LoginForm = ({
  handleChange,
  handleBlur,
  handleSubmit,
}) => (
  <form onSubmit={handleSubmit}>
    <input
      onChange={handleChange}
      onBlur={handleBlur}
    />
    <input
      onChange={handleChange}
      onBlur={handleBlur}
    />
    <button type="submit">
      Submit
    </button>
  </form>
);

const shape = { email: '', password: '', generic: '' };

LoginForm.propTypes = {
  handleChange: PropTypes.func,
  handleBlur: PropTypes.func,
  handleSubmit: PropTypes.func,
};

LoginForm.defaultProps = {
  handleChange: () => {},
  handleBlur: () => {},
  handleSubmit: () => {},
};

export default LoginForm;

原文由 Rutul Patel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 517
2 个回答

如果您想测试这些函数是否具有预期的行为,您可以将它们作为 LoginForm 上的静态属性进行访问,并围绕它编写测试。

 import LoginForm from 'wherever'

test('should have default handleChange', () => {
   expect(LoginForm.defaultProps.handleChange).toBeDefined();
});

test('something something', () => {
    const result = LoginForm.defaultProps.handleChange();
    expect(result).toBe('something');
});

如果你想测试 React 是否按照它所说的去做——也就是说,如果没有指定其他道具,它会传递默认道具——我建议你不要这样做。 React 的创建者围绕它 编写了测试

原文由 Nicholas Tower 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用酶的 mount.props() 访问道具。

 import LoginForm from '../somelocation'
import { mount } from 'enzyme'

it('should handleChange when value 'foo' is passed', () => {
   const props = mount(<LoginForm />).props()
   const handleChange = props.handleChange
   expect(handleChange('foo')).to.equal('bar')
 }

const defaultProps 应该给你

props = {
   handleChange: () => {},
   handleBlur: () => {},
   handleSubmit: () => {}
}

原文由 dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题