Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda