我正在尝试为以下组件编写测试
class LoanApplication extends Component {
constructor(props) {
super(props);
}
canApplyLoan = () => {
const {dob, nric, loanAmount, selectedLoanTerm, selectedLoanType, fullName} = this.props.data;
return dob.length && nric.length && loanAmount.length && loanAmount > '0' && selectedLoanTerm.length && selectedLoanType.length && fullName.length;
};
render() {
this.props.data.enableLoanForm = this.canApplyLoan();
return (
<div className='mainApplication'>
<h4>Apply for a Loan</h4>
<form onSubmit={this.props.loanSubmission} className='loanApp'>
<div className="form-group">
<label htmlFor="exampleInputFullName">Full Name</label>
<input type="text" className="form-control" id="exampleInputFullName"
aria-describedby="fullNameInfo" placeholder="Enter Full Name"
onChange={this.props.fullNameChange}/>
</div>
<div className="form-group">
<label htmlFor="datepicker">Date Of Birth</label>
<input type="date" id="datepicker" aria-describedby="dobInfo" className="form-control"
placeholder="DOB" onChange={this.props.dobChange}/>
</div>
<button className='btn loanBtn' disabled={!this.props.data.enableLoanForm}>Submit
</button>
</form>
................
我的测试代码
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import LoanApplication from '../LoanApplication';
describe('LoanApplicationComponent', () => {
it('should render without throwing error', () => {
expect(shallow(<LoanApplication/>).find('form.loanApp').exists()).toBe(true);
});
});
运行笑话测试时出现以下错误
FAIL src/components/__tests__/LoanApplication-test.js
● LoanApplicationComponent › should render without throwing error
TypeError: Cannot read property 'dob' of undefined
7 |
8 | canApplyLoan = () => {
> 9 | const {dob, nric, loanAmount, selectedLoanTerm, selectedLoanType, fullName} = this.props.data;
| ^
10 | return dob.length && nric.length && loanAmount.length && loanAmount > '0' && selectedLoanTerm.length && selectedLoanType.length && fullName.length;
11 | };
12 |
我不确定测试为什么失败,我是否需要对通过道具接收的数据进行特定的处理。请指教
答案 0 :(得分:1)
组件尝试读取一堆道具,但您没有通过它们:
shallow(<LoanApplication/>)
。
您应该:
a)指定defaultProps
:
LoanApplication.defaultProps = {
data: {...}
}
或:
b)在测试中通过一些值:
shallow(<LoanApplication data={...} />))