I'm currently writing a React component in Typescript which makes use of a axios-hooks hook called useAxios. An example of this hook in use is here:
export const App = () => {
const [{ data, loading, error }, refetch] = useAxios(
"https://api.myjson.com/bins/820fc"
);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return (
<div>
<button onClick={e => refetch()}>refetch</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
const rootElement = document.getElementById("root");
render(<App />, rootElement);
I'm trying to figure out how to write a test where I can mock the useAxios hook. I've tried creating a mock of the underlying axios component but I cant get this working:
import React from "react"
import { render } from "@testing-library/react"
import { Test } from "../test"
import useAxios from "axios-hooks"
jest.mock("axios-hooks")
const mockedAxios = useAxios as jest.Mocked<typeof useAxios>
it("Displays loading", () => {
// How to mock the return values in the following line?
// mockedAxios.
const { getByText } = render(<Test />)
expect(getByText("Loading...")).toBeDefined()
})
I know that I shouldn't have to mock axios which is the underlying dependency, I should be able to mock useAxios, but I though I'd try anyhow.
I realise that this question has been mentioned many times on SO, but I can find a solution to this particular use case.
Any help greatly appreciated!
jest.mock("axios-hooks")and lateruseAxious.mockResolvedValue(dataToRespond)? or do you need dynamic mocking based on URL?