Angular 15中如何在Jest测试中检测@angular/google-maps的mapClick事件?
解决Angular Google Maps组件mapClick事件的Jest测试问题
核心思路
mapClick是@angular/google-maps暴露的自定义输出事件,而非原生DOM点击事件,所以不能用fireEvent.click触发。需要直接获取<google-map>元素,手动派发对应的自定义事件。
具体实现步骤
创建Jest Spy监听addShape方法
在测试用例中先对组件的addShape方法创建spy,确保能追踪调用情况:const addShapeSpy = jest.spyOn(component, 'addShape');获取google-map组件元素
通过测试夹具的nativeElement找到<google-map>元素:const googleMapElement = fixture.nativeElement.querySelector('google-map');手动派发mapClick自定义事件
构造符合组件预期的事件对象(比如包含latLng属性,和实际mapClick事件返回的结构一致),然后派发事件:const mockMapClickEvent = { latLng: { lat: () => 39.9, lng: () => 116.4 } // 模拟经纬度数据 }; googleMapElement.dispatchEvent(new CustomEvent('mapClick', { detail: mockMapClickEvent }));触发变更检测并断言
触发Angular的变更检测,然后验证spy是否被调用:fixture.detectChanges(); expect(addShapeSpy).toHaveBeenCalledWith(mockMapClickEvent);
完整测试代码示例
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MapComponent } from './map.component'; import { GoogleMapsModule } from '@angular/google-maps'; describe('MapComponent', () => { let component: MapComponent; let fixture: ComponentFixture<MapComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [GoogleMapsModule], declarations: [MapComponent] }).compileComponents(); fixture = TestBed.createComponent(MapComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should call addShape when mapClick event is triggered', () => { // 创建spy const addShapeSpy = jest.spyOn(component, 'addShape'); // 获取google-map元素 const googleMapElement = fixture.nativeElement.querySelector('google-map'); // 模拟事件数据 const mockEvent = { latLng: { lat: () => 40, lng: () => 116 } }; // 派发自定义事件 googleMapElement.dispatchEvent(new CustomEvent('mapClick', { detail: mockEvent })); // 触发变更检测 fixture.detectChanges(); // 断言方法被调用 expect(addShapeSpy).toHaveBeenCalledWith(mockEvent); }); });
注意事项
- 确保事件对象的结构和
mapClick实际返回的一致,否则组件内的addShape方法可能无法正确处理参数。 - 如果测试时遇到
<google-map>元素未渲染的问题,可检查GoogleMapsModule是否正确导入到测试模块中。
内容的提问来源于stack exchange,提问作者Frank Luke
相关产品推荐
相关产品推荐

