Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

68
Vistas
testing with jest to update a react state inside a rejected promise

This is a continuation of this question. I have made a few changes that simplifies the question(I believe) and changes it drastically.

I have seperated creating the hook and initialization of midi events.

describe("midiConnection", () => {
    it("Should fail", () => {
        const midiPorts = renderHook(() => { return MidiConnection()})
        act(() => {
            midiPorts.result.current.enable()
        })
        console.log(midiPorts.result.current.error)
    })
})
export function MidiConnection() {
    const {array: midiInputs, push: midiPush, filter: midiFilter} = useArray(["none"])
    const [error, setError] = useState<Error | undefined>();
    function enable() {
        WebMidi.addListener("connected", (e) => { if (isInput(e)) {midiPush(e.port.name)}});
        WebMidi.addListener("disconnected", (e) => {
            e.port.removeListener()
            if (isInput(e)) {midiFilter((str) => {return str != e.port.name})}
        });
        // setError("this is a test")
        WebMidi.
        enable().
        catch((err) => {
            // console.log("test")
            // setError(err)
        })
    }
    return ({ports: midiInputs, error, enable})
}

the warning is still;

Warning: An update to TestComponent inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */

In addition to seperating out some of the logic I have also experimented with placing setError() on other lines to see if I can trigger the warning (the commented out comments.)

It appears that the warning is only triggered when I try to update the state when the promise from enable() is rejected.

What can I do to stop this error from happening?

EDIT: I have created a working replica of this in CodeSandbox, which you will see if you go to tests and look at the console.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your hook is async so u need to wait for the next update. Here is the docs that talks more about it.

import { renderHook, act } from "@testing-library/react-hooks/dom";
import CHook from "./../hook/CHook";

test("This is a test", async () => {
  const { result, waitForNextUpdate } = renderHook(() => CHook());
  act(() => {
    result.current.update();
  });
  await waitForNextUpdate();
  console.log(result.current.error);
});

Here is the link to a fixed sandbox.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda