2

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;
Kerron
  • 396
  • 5
  • 10

1 Answers1

2

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

ourmaninamsterdam
  • 1,915
  • 15
  • 11
  • I'm getting an `ReferenceError: google is not defined` when I try to run that. Error happens on line `render();` – Kerron Feb 22 '22 at 19:58
  • If you replace the `` from `` with just text content, e.g. 'some map content', do you still get the error? I'm not sure of the internals of @react-google-maps/api but you may need to do some further mocking of the other @react-google-maps/api dependencies to get it working. – ourmaninamsterdam Feb 23 '22 at 12:37
  • @Kerron you can mock `google` namespace using `global` object, for example `global.google = { maps: { Map: jest.fn(), Marker: jest.fn() } } as unknown as typeof google;` – callmenikk Sep 14 '22 at 09:48