Testing Components Using @vis.gl/react-google-maps & @googlemaps/jest-mocks #204
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
In general you should try to avoid testing what this library does and focus on what you are doing with the library. For example – if all you need is the map, you can essentially mock it without any functionality: const MapMock = jest.fn(() =>
React.createElement('div', { 'data-testid': 'map-mock' })
); With this you can inspect the The same goes for child-components like
Everything beyond that shouldn't be your concern, and we'll take it from there :) Now, if your code has to interact with the Google Maps API objects, like the actual import { initialize } from '@googlemaps/jest-mocks';
beforeEach(() => {
initialize();
}); Then you need to create a mock for the useMap function that returns a mocked const useMapMock = jest.fn(() => {
// the global google.maps namespace is provided by the @googlemaps/jest-mocks package
return new google.maps.Map();
}); Now, in your test, you can retrieve the mocked map object and use it: import {mockInstances} from '@googlemaps/jest-mocks';
test("something", () => {
// [...run the code that uses the useMap hook]
// retrieve the mock instance created in useMapMock
const map = mockInstances.get(google.maps.Map).at(-1)!;
// run assertions
}); Quite often, even that isn't enough, since you sometimes need to control the return value of a map-function or test how your application reacts to events. In those cases you need to extend the mocked google.maps.Map class to do that. I wrote a bit more about how to do that here: https://github.com/googlemaps/js-jest-mocks/#usage I hope this helps you get started, and let me know if there are more questions. |
Beta Was this translation helpful? Give feedback.
So here's a very rough sketch:
I'm assuming
jest
+@testing-library/react
as testing framework (the idea applies to any other setup as well).Suppose a component (much simpler than your example, but I hope that's enough to illustrate the point) like this:
So what do we need to test here? When testing the
CustomMarker
component, the only thing we need to verify is that the co…