Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Testing if a prop function was called using react-testing-library and jest

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;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!