I have a simplified exemple of what i try to accomplish :
// ResourceRouter.ts
class ResourceRouter extends ResourceApi {
static init(token: string) {
return new ResourceRouter(token)
}
public async getResource (id: number) {
try {
const res : AxiosResponse<Resource> await this.get("/my-endpoint-url", id)
return res.data
} catch (error: unknown) { throw error; }
}
}
// useGetResource.ts
const useGetResource = () => {
const resourceRouter = ResourceRouter.init("my_token")
const queryOpts = queryOptions({
queryKey:["get_resource"]
queryFn: () => resourceRouter.getResource(1)
})
const query = useQuery(queryOpts)
return query
}
// useGetResource.test.ts
const ResourceRouteInitSpy = vi.spyOn(ResourceRouter, "init");
describe("useGetResource", () => {
it("Should get resource with correct id", async () => {
const { result } = renderHook(() => useGetResource(), { wrapper: QueryClientWrapper })
expect(resourceRouterInitSpy).toHaveBeenCalledWith("token_mock") // called
const resourceRouterGetResourceSpy = vi.spyOn(ResourceRouter.prototype, "getUser")
await waitFor(() => expect(ResourceRouterGetResourceSpy).toHaveBeenCalled()) // not called
})
})
In my test file, I try to spy on my resourceRouter.getResource
instance method to ensure that it has been called with a specific id. I can do that for the static init
method, but not with the getResource
method from the prototype. Why ?
I tried to expose the resourceRouter instance in the return value of my custom hook so i can access it from the test file, but the method seems not to be called either.
Regards,