I am trying to write a simple test to verify that a prop was called when user interacts with a couple buttons. Here is my test:
it('submits the name on save', async () => {
const name = 'Some name'
const updatedName = 'New name'
const onSubmit = jest.fn()
render(
<EditableName name={name} onSubmit={onSubmit} />
)
act(() => {
fireEvent.click(getByText('Edit'))
fireEvent.change(getByRole('input'), { target: { value: updatedName } })
fireEvent.click(getByText('Save'))
})
expect(onSubmit).toBeCalledTimes(1)
})
Result:
● EditableName › submits the name on save
expect(jest.fn()).toBeCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
When I console.log to see if the line that calls onSubmit is being reached, I can see that it is.
I am suspecting the problem is that the onSubmit function I'm expecting is a different instance of the function by the time I'm asserting .toBeCalledTimes(). Because of the three events that I am firing cause the component to re-render.
How can I make sure the function that I am passing as a prop in the test is the same one that is being called? Do I need to use spyOn? If so, how?
Thanks in advance!
Edit: Here is the minimal code example of the component:
import React, { useState } from "react";
import { Box, Button, TextField, Typography } from "@material-ui/core";
const EditableName = ({ name, onSubmit }) => {
const [editing, setEditing] = useState(false);
const [value, setValue] = useState(name);
const handleSubmit = () => {
onSubmit({ name: value });
};
const handleToggleEditMode = () => {
if (editing) {
setEditing(false);
setValue(name);
} else {
setEditing(true);
}
};
if (!editing) {
return (
<>
<Typography display="inline" variant="h5" component="h1">
{name}
</Typography>
<Button onClick={handleToggleEditMode}>
Edit
</Button>
</>
);
}
return (
<>
<TextField
name="name"
variant="outlined"
fullWidth
size="small"
label="Subsidy name"
value={value}
onChange={(e) => setValue(e.target.value)}
inputProps={{ role: "input" }}
/>
<Button onClick={handleSubmit}>Save</Button>
</>
);
};
export default EditableName;
I think you need to separate the events, and act is built into RTL so you need to use await waitFor instead:
await waitFor(() => {
fireEvent.click(getByText('Edit'))
});
//should probably assert changes here
await waitFor(() => {
fireEvent.change(getByRole('input'), { target: { value: updatedName } })
});
//should probably assert changes here
await waitFor(() => {
fireEvent.click(getByText('Save'))
})
expect(onSubmit).toBeCalledTimes(1)