You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何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.

Common Mocking Solutions (Framework-Agnostic + Jest-Specific)

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)
    })
  }
};
How to Verify It's Working

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);
Quick Troubleshooting Tip

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:52:11