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.
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);
});