In my React Signup component is a form where the user inputs their email, password, and password confirmation. I am trying to write tests using jest/react-testing-library, however I keep getting a test failed as the received number of function calls is 0 with an expected number of calls being 1.
I have tried variations of the Jest matcher such as .toHaveBeenCalled(), .toHaveBeenCalledWith(arg1, arg2, ...), toBeCalled() all of which still expect a value of 1 or greater but fail because the received number is 0. I have tried both fireEvent.click and fireEvent.submit both of which still fail.
Signup.js
export const Signup = ({ history }) => {
const classes = useStyles();
const [signup, setSignup] = useState({
email: null,
password: null,
passwordConfirmation: null,
});
const [signupError, setSignupError] = useState('');
const handleInputChange = e => {
const { name, value } = e.target;
setSignup({ ...signup, [name]: value });
console.log(signup);
};
const submitSignup = e => {
e.preventDefault();
console.log(
`Email: ${signup.email}, Pass: ${signup.password}, Conf: ${signup.passwordConfirmation}, Err: ${signupError}`
);
};
return (
<main>
<form onSubmit={e => submitSignup(e)} className={classes.form}>
<TextField onChange={handleInputChange}/>
<TextField onChange={handleInputChange}/>
<TextField onChange={handleInputChange}/>
<Button
type="submit">
Submit
</Button>
Signup.test.js
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { render, cleanup, fireEvent } from '@testing-library/react';
import { Signup } from '../Components/Signup';
afterEach(cleanup);
const exampleSignup = {
email: '[email protected]',
password: 'test123',
passwordConfirm: 'test123',
};
describe('<Signup />', () => {
test('account creation form', () => {
const onSubmit = jest.fn();
const { getByLabelText, getByText } = render(
<BrowserRouter>
<Signup onSubmit={onSubmit} />
</BrowserRouter>
);
const emailInput = getByLabelText(/Enter your Email */i);
fireEvent.change(emailInput, { target: { value: exampleSignup.email } });
const passInput = getByLabelText(/Create a Password */i);
fireEvent.change(passInput, { target: { value: exampleSignup.password } });
const passCInput = getByLabelText(/Confirm Password */i);
fireEvent.change(passCInput, {
target: { value: exampleSignup.passwordConfirm },
});
fireEvent.submit(getByText(/Submit/i));
expect(onSubmit).toHaveBeenCalledTimes(1);
});
});
Results from test run account creation form
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0