如何Mock谷歌地图addEventListener?测试遇this.map.addListener非函数错误
Hey Marina, let's sort out that this.map.addListener is not a function error you're hitting! The root issue here is that your mocked map object doesn't have the addListener method defined—so we just need to update your mock to include it, along with any related functionality your code uses.
Option 1: Manual Mock (Works with Any Testing Framework)
Create a mock map object that explicitly includes the addListener method, plus the remove method if your code cleans up listeners later:
// Build your mock map instance const mockMap = { addListener: (eventType, callback) => { // Optional: Store callbacks if you need to trigger events manually in tests mockMap[`${eventType}Callback`] = callback; // Return the listener object with a mock remove method return { remove: () => {} // Use jest.fn() instead if you're using Jest for assertions }; } }; // Assign this mock to wherever your component's `this.map` is set // Example: If your component initializes the map in a constructor, replace that with the mock yourComponent.map = mockMap;
Option 2: Jest-Specific Global Mock
If you're using Jest, you can mock the entire google.maps global object once, so it's available across all your tests:
// Add this at the top of your test file, or in a __mocks__/google.maps.js file global.google = { maps: { // Mock the Map constructor to return our mock map instance Map: jest.fn().mockReturnValue({ addListener: jest.fn((event, cb) => ({ remove: jest.fn() })) // Add other map methods your code uses here (e.g., setCenter, fitBounds) }) } };
After setting up the mock, you can assert that addListener is being called correctly:
// Example test assertion (Jest syntax) expect(mockMap.addListener).toHaveBeenCalledWith('click', expect.any(Function)); // If you stored the callback, you can even trigger it to test your handler mockMap.clickCallback({ latLng: { lat: () => 40.7128, lng: () => -74.0060 } }); expect(yourComponent.someState).toBe(updatedValue);
Double-check where this.map is being initialized in your code. If it's created via new google.maps.Map(...), make sure your mock constructor is returning the object with addListener—that's the most common spot where this error pops up!
内容的提问来源于stack exchange,提问作者Marina

