'How can I test functions that are inside a component
is there a way to test functions that are inside components.
For my example I have a component called LoginPopUp inside the component there is a login form:
<div data-testid="popup" className="popup-content">
<h3 className="title">Login form </h3>
<form>
<div className="form-group">
<input data-testid="email" name="email" placeholder="Email" className="form-control"
type="email" onChange={e => setEmail(e.target.value)}/>
</div>
<div className="form-group">
<input data-testid="password" name="password" placeholder="Password" className="form-control"
type="password" onChange={e => setPassword(e.target.value)}/>
</div>
<button data-testid="loginBtn" onClick={handleLogin} type={"submit"}
className="popup-btn-login">Login
</button>
</form>
</div>
as you can see this is my form and the login button is type submit, the button calls handleLogin on click here is the function
function handleLogin(event) {
event.preventDefault();
if (email === '[email protected]' && password === '123') {
localStorage.setItem('token', true);
localStorage.setItem('email', email)
closePopup(false)
} else {
closePopup(true);
setError(true);
}
}
I wrote tests for the component itself but I want to test the behavior of the handleLogin in case of success and failure of the login
Solution 1:[1]
I don't get your point? If you want to test how the function works when it's successful, just enter the current email and password and if you want to test when it's failed, just enter the wrong input.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chaukhoa97 |
