我正在尝试使用带有酶的props测试类组件,但出现以下错误:
<FormUserDetails /> rendering › FormUserDetails: renders correctly
TypeError: Cannot read property 'formErrors' of undefined
23 | <input
24 | id="input-form-name"
> 25 | className={values.formErrors.name.length > 0 ? "error" : null}
我认为问题可能出在通过测试的道具上:我如何告诉酶寻找价值?
我是酶的新手,所以我想知道我缺少什么。以下是相关代码:
这是我正在测试的组件:
import React, { Component } from 'react'
export class FormUserDetails extends Component {
// Go to the next page on submit
continue = e => {
e.preventDefault()
this.props.nextStep()
}
render() {
const {values, handleChange, nextStep } = this.props
return (
<div className="wrapper">
<div className="form-wrapper">
<div className='page-detail'>
<h3 className="alignleft">User Details</h3>
<p className="aligncenter">Privacy</p>
<p className="alignright">Done</p>
</div>
<form className="form">
<div className="name">
<input
id="input-form-name"
className={values.formErrors.name.length > 0 ? "error" : null}
placeholder="Name *"
type="text"
name="name"
noValidate
onChange={handleChange}
/>
{values.formErrors.name.length > 0 && (
<span className="errorMessage">{values.formErrors.name}</span>
)}
</div>
<div className="role">
<input
id="input-form-role"
placeholder="Role"
type="text"
name="role"
onChange={handleChange}
/>
</div>
<div className="email">
<input
id="input-form-email"
className={values.formErrors.email.length > 0 ? "error" : null}
placeholder="Email *"
type="email"
name="email"
onChange={handleChange}
/>
{values.formErrors.email.length > 0 && (
<span className="errorMessage">{values.formErrors.email}</span>
)}
</div>
<div className="password">
<input
id="input-form-password"
className={values.formErrors.password.length > 0 ? "error" : null}
placeholder="Password *"
type="password"
name="password"
onChange={handleChange}
/>
{values.formErrors.password.length > 0 && (
<span className="errorMessage">{values.formErrors.password}</span>
)}
</div>
</form>
<button id='btn-next' onClick={nextStep}>Next</button>
<br/>
<small><i>Fields marked with * are required</i></small>
</div>
</div>
)
}
}
export default FormUserDetails
这是我的测试:
import React from 'react';
import renderer from 'react-test-renderer';
import FormUserDetails from '../components/FormUserDetails';
describe('<ForUserDetails /> rendering', () => {
it('ForUserDetails: renders correctly', () => {
const tree = renderer.create(
<FormUserDetails
values={{formErrors: { name: '', email: '', password: ''}}}
handleChange={() => {}}
nextStep={() => {}}
/>).toJSON()
expect(tree).toMatchSnapshot();
});
});
答案 0 :(得分:0)
因为您希望在此处使用内部组件:
const {values, handleChange, nextStep } = this.props
道具values
将通过,但在测试中您无需这样做。
因此,您必须在测试内部将props传递到组件(在您的示例中应该是:const tree = renderer.create(<FormUserDetails values={ formErrors: { name: '', email: '', password: '' } } handleChange={() => {}} nextStep={() => {}} />).toJSON()
);