【发布时间】: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。上面的内容不是一个函数,因为它正在寻找Provider 的instance,这不是我想要做的。但是,render 没有 Provider 的组件(在测试中)会引发错误,即组件必须包装在 Provider!
有谁知道我在哪里出错了......?任何帮助将不胜感激,因为我在这里处于合法的停顿状态......
提前致谢!!
【问题讨论】:
标签: reactjs unit-testing react-redux jestjs redux-form