使用酶和开玩笑,如果我想让 props 设置具有 1 个或多个输入的组件的默认输入值,我如何访问输入以验证其文本值?
使用以下示例,未找到任何节点,并且出现错误
Method “text” is meant to be run on 1 node. 0 found instead.
注册组件:
import React, { Component } from "react";
import { Form, Row } from "react-bootstrap";
class Register extends Component {
constructor() {
super();
this.state = {
username: "",
password: ""
};
}
componentDidMount() {
this.setState({
username: this.props.username,
password: this.props.password
})
}
onChange = (event) => {
this.setState({
[event.target.id]: event.target.value
})
}
render() {
var registerInformation = []
const registerValueItems = []
const registerLabelItems = []
registerLabelItems.push(<div key={"username"} className="labelitem"><Form.Label>Username:</Form.Label></div>)
registerLabelItems.push(<div key={"password"} className="labelitem"><Form.Label>Password:</Form.Label></div>)
registerValueItems.push(<Row key={"username"}><Form.Control id="username" value={this.state.username} disabled={!this.state.edit} onChange={this.onChange}/></Row>)
registerValueItems.push(<Row key={"password"}><Form.Control id="password" value={this.state.password} disabled={!this.state.edit} onChange={this.onChange}/></Row>)
registerInformation = (
<div id="registerinfoarea" className="registerinfoarea">
<div id="registerlabelarea" className="labelarea">{registerLabelItems}</div>
<div id="registervaluearea" className="valuearea">{registerValueItems}</div>
</div>
)
return (
<div id="registerarea" className="registerarea">
{registerInformation}
</div>
);
}
}
export default Register;
测试
it("renders with username", () => {
const props = {username: "Santa Clause", password: "presents"}
const RegisterComponent = mount(<Register {...props}/>);
expect(RegisterComponent.find('username').text()).toEqual('Santa Clause')
});
你应该使用 Enzyme 的 .find(( 方法来查找<Row />
组件(我假设Row
组件在此组件中只呈现一次(。
expect(RegisterComponent.find(Row).text()).toEqual('Santa Clause')
这将允许您查找与该组件匹配的节点。