I have this basic component, but whenever I try testing it with React Testing Library the only thing present on the screen is the div
with the "loading" text. I think this is because isLoaded
might not have a value when the component is first loaded.
How do I tell React Testing Library to wait until isLoaded
is true
so it can find other elements on the page?
import {
GoogleMap,
useJsApiLoader,
Autocomplete,
Marker,
} from "@react-google-maps/api";
export const Map = () => {
const { isLoaded } = useJsApiLoader("apikey");
return isLoaded ? (
<form>
<Autocomplete />
<GoogleMap>
<Marker />
</GoogleMap>
</form>
) : (
<div>loading</div>
);
};
export default Map;
You need to stub the isLoaded
in useJsApiLoader
.
Something like this approach (I've not tested this and you'd need to adjust the assertions to your requirements)...
import { screen, render } from "@testing-library/react";
import Map from "./Map";
import * as ReactGoogleMapsApi from "@react-google-maps/api";
describe("Map", () => {
it("shows loader", () => {
jest
.spyOn(ReactGoogleMapsApi, "useJsApiLoader")
.mockReturnValue({
isLoaded: false
});
render(<Map />);
expect(screen.getByText(/loading/i)).toBeInDocument();
});
it("shows map", () => {
jest
.spyOn(ReactGoogleMapsApi, "useJsApiLoader")
.mockReturnValue({
isLoaded: true
});
render(<Map />);
expect(screen.getByText(/some map content/i)).toBeInDocument();
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.