'How to test api is triggered or not in jest with testing react library
Login.js
import {useSelector, useDispatch } from 'react-redux';
import Header from './Header';
import {submitForm, handleChange} from '../actions/authentication';
const Loginheader = () => {
const selector = useSelector(state => state.authentication);
const dispatch = useDispatch();
const submitFormagin = (e) => {
e.preventDefault();
let params = {
email : selector.email.replace(/\s/g, '').toLowerCase(),
password : selector.password.replace(/\s/g, ''),
user_ip : selector.login_ip
}
//Hit api
dispatch(submitForm(params,"login"))
}
return(
<>
<Header/>
<section className="height100 create-account">
<div className="signup_left">
<div className="white-bg">
<div className="signup_form">
<form onSubmit = {e => submitFormagin(e)} data-testid="form">
<div className="form-group">
<input type="text" data-testid = "email" className="form-control" name="email" placeholder="Email*" value={selector.email} onChange = {e => dispatch(handleChange(e))}/>
</div>
<div className="form-group">
<input type={selector.passattibutetype} data-testid = "password" className="form-control eye-close" name="password" placeholder="Password*" value={selector.password} onChange = {e => dispatch(handleChange(e))}/>
</div>
<button type="submit" className="loginbtn" data-testid = "button">
<div className="d-flex align-items-center justify-content-center h-100 w-100">
<div className={selector.loader}>
<img src={selector.loaderimage} alt="loader"/>
</div>
<div>
{selector.submitval}
</div>
</div>
</button>
</form>
</div>
</div>
</div>
</section>
</>
)
}
export default Loginheader;
Login.test.js
import { render, fireEvent, cleanup, waitFor } from '@testing-library/react';
import Loginheader from './Login';
import store from '../store';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
describe("Login", () => {
afterEach(cleanup);
test("Check Snapshot", () => {
const {container} = render(<BrowserRouter><Provider store={store}><Loginheader /></Provider></BrowserRouter>)
expect(container).toMatchSnapshot();
})
test("Form submit", async () => {
const { getByTestId} = render(<BrowserRouter><Provider store={store}><Loginheader /></Provider></BrowserRouter>)
const emailval = "xyz";
fireEvent.change(getByTestId('email'), { target : {
value:emailval
}});
fireEvent.change(getByTestId('password'), { target : {
value:"123456"
}});
fireEvent.submit(getByTestId('form'));
await waitFor(() => {
expect(getByTestId('password').value).toBe(emailval)
expect(getByTestId('email').value).toBe(emailval)
})
})
})
How to test api is triggered or not in jest with testing react library?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|