【发布时间】:2019-04-27 06:58:46
【问题描述】:
我正在尝试为以下组件编写测试
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 |
我不确定为什么测试失败,我是否需要针对通过道具接收的数据做一些具体的事情。请指教
【问题讨论】:
-
组件试图读取一堆道具,但你在这里没有通过它们:
shallow(<LoanApplication/>)。您应该为组件指定defaultProps或在shallow()中传递一些值