-
I have a prod code like this: const myHook = () => {
const [error, setError] = useState("");
const { data } = useSWR(url, fetcher, {
onError: (error) => {
setError(error);
},
});
return { data, error, setError };
}; then I want to mock this error and perform an assertion for error message changing: import { renderHook } from "@testing-library/react-hooks";
describe("#myHook", () => {
it("should set error message when request failed", async () => {
// given
const useSWR = jest.fn().mockReturnValue(Error("error"));
jest.doMock("swr", () => useSWR);
const { myHook } = require("../myHook");
// when
const { result, waitForNextUpdate } = renderHook(() => myHook());
await waitForNextUpdate;
// then
expect(result.current.error).toBe("error");
});
}); and it does not work, so my question is how to mock useSWR's error, so I can trigger onError callback Thanks. |
Beta Was this translation helpful? Give feedback.
Answered by
sergiodxa
Sep 12, 2020
Replies: 1 comment 1 reply
-
Your fetcher function should throw an error, not the hook itself, also you can access the error with const { data, error } = useSWR(key, fetcher) You don’t need to create a different state and use onError to update it. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
teobler
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your fetcher function should throw an error, not the hook itself, also you can access the error with
You don’t need to create a different state and use onError to update it.