我正在为组件编写 Jest,以确保单击按钮时将执行handleLogin。不知道为什么我不断收到 jest.fn() 未执行一次的错误。我在这里删除了大部分不必要的代码
class Login extends React.Component{
constructor(props){
super(props);
this.state = { }
this.handleLogin = this.handleLogin.bind(this);
}
handleLogin(e){
e.preventDefault();
const { email, password, invalidEmail, invalidPassword } = this.state;
if(!invalidEmail && !invalidPassword){
userAPI.login({email, password}).then(data=>{
window.localStorage.setItem('email',data.email);
window.localStorage.setItem('password',data.password);
}).catch(error=>{
this.setState({
incorrectCredential: true // login failed due to wrong credential
})
})
}else{
this.setState({
invalidCredential: true // login failed due to wrong format
})
} // login failed
}
render(){
return(
<header>
<div className="login" data-test="login">
<button className="login_content_main_join" type="submit" onClick={this.handleLogin} data-test="submit">Log in</button>
</div>
</header>
)
}
export default Login;
Run Code Online (Sandbox Code Playgroud)
这是我的测试部分
it('Login/click to trigger this.handleLogin()', ()=>{
const wrapper = shallow(<Login />);
const instance = wrapper.instance();
jest.spyOn(instance, 'handleLogin');
findTestWrapper(wrapper, 'submit').simulate('click', {
preventDefault: ()=> {}
});
expect(instance.handleLogin).toHaveBeenCalled();
})
Run Code Online (Sandbox Code Playgroud)
我已经验证了handleLogin()可以通过模拟“点击”来执行,通过向其中添加console.log(“run”),但我不断收到如下错误。
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
26 | preventDefault: ()=> {}
27 | });
> 28 | expect(instance.handleLogin).toHaveBeenCalled();
| ^
29 | })
Run Code Online (Sandbox Code Playgroud)
考虑监视组件并在包装器上prototype使用内置方法.find
it("Login/click to trigger this.handleLogin()", () => {
const wrapper = shallow(<Login />);
const spy = jest.spyOn(Login.prototype, "handleLogin"); // spying on the Component prototype
wrapper.find('button.login_content_main_join').simulate('click'); // use .find method on wrapper
expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11692 次 |
| 最近记录: |