Reactjs 仅使用Jest测试有状态反应成分(不使用反应测试库或酶)
是否可以只使用Jest测试有状态的react组件?我找不到任何不使用任何其他库(如酶或反应测试库)就能实现这一点的例子 我想测试的示例代码Reactjs 仅使用Jest测试有状态反应成分(不使用反应测试库或酶),reactjs,jestjs,Reactjs,Jestjs,是否可以只使用Jest测试有状态的react组件?我找不到任何不使用任何其他库(如酶或反应测试库)就能实现这一点的例子 我想测试的示例代码 import React,{Component} from 'react'; class SampleComponent extends Component { constructor(props) { super(props) this.state = { username: '', password: ''
import React,{Component} from 'react';
class SampleComponent extends Component {
constructor(props) {
super(props)
this.state = {
username: '',
password: '',
loginMessage: ''
}
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(event) {
this.setState({
[event.target.name] : event.target.value
})
}
onSubmit(event) {
if(this.state.password === 'password') {
this.setState({
loginMessage: 'Login Successfully'
})
} else {
this.setState({
loginMessage: 'Login Failed due to incorrect password'
})
}
event.preventDefault();
}
render() {
return (
<React.Fragment>
<p>Hello React!!!</p>
<form onSubmit={this.onSubmit}>
<input placeholder="user" type="text" name="username" value={this.state.username} onChange={this.onChange}/>
<input placeholder="password" type="password" name="password" value={this.state.password} onChange={this.onChange}/>
<button type="submit">Submit</button>
</form>
<h6>{this.state.loginMessage}</h6>
</React.Fragment>
);
}
}
export default SampleComponent
import React,{Component}来自'React';
类SampleComponent扩展组件{
建造师(道具){
超级(道具)
此.state={
用户名:“”,
密码:“”,
登录消息:“”
}
this.onChange=this.onChange.bind(this);
this.onSubmit=this.onSubmit.bind(this);
}
onChange(事件){
这是我的国家({
[event.target.name]:event.target.value
})
}
提交(事件){
如果(this.state.password==='password'){
这是我的国家({
登录消息:“登录成功”
})
}否则{
这是我的国家({
loginMessage:“由于密码不正确,登录失败”
})
}
event.preventDefault();
}
render(){
返回(
你好,反应
提交
{this.state.loginMessage}
);
}
}
导出默认采样组件
从技术上讲,它只是一个类,因此您可以始终通过测试中的new
操作符创建它的新实例:new SampleComponent(props)
,然后对其调用一些方法或访问状态
然而,你为什么要这样做?您找不到任何示例的原因是tt测试这样的组件是非常糟糕的做法。您缺少了这些库提供的很多东西,您必须自己编写代码。它无法正确安装,因此状态可能无法正常工作。您正在测试实现细节(看看为什么这是个坏主意)
若你们只是不喜欢酶或反应测试库,你们可以随时从反应团队检查较低的水平
我不知道您的具体情况,但我确实建议使用一些库,因为它可以简化测试。感谢您的解释,我将计划使用这些库中的任何一个。