首页 > 解决方案 > 如何对实现 ArcGIS API for Angular 的类进行单元测试?

问题描述

我正在使用 esri-loader 构建一个 Angular 8 应用程序,并且我真的很难在我的测试中找出模拟 ArcGIS JS API 依赖项的最佳方法。我遇到的应用程序示例代码非常少,这些应用程序是使用除 dojo 之外的框架构建的,这些框架使用 ArcGIS JS API 并且还包含有意义的单元测试。 有没有人成功地做到这一点并能够提供一些指导?

例如,假设我有一个如下所示的 MapComponent 类:

export class MapComponent {
mapView: MapView;

public async initializeMap(lat: number, lon: number, zoom: number) {
const [Map, MapView] = await loadModules(['esri/Map', 'esri/views/MapView']);

this.mapView = new MapView({
   zoom: zoom,
   center: [lat, lon]
  map: new Map({
    basemap: 'streets'
  })
});
}

public async addPointToMap(lat: number, lon: number) {
const [Graphic] = await loadModules(['esri/Graphic']);
 
 const point = {
   type: "point",
   longitude: lon,
   latitude: lat
 };

 const markerSymbol = {
   type: "simple-marker",
   color: [226, 119, 40],
   outline: {
      color: [255, 255, 255],
      width: 2
   }
 };

 const pointGraphic = new Graphic({
   geometry: point,
   symbol: markerSymbol
 });
 
 this.mapView.graphics.add(pointGraphic);
 }
}

我想测试 initializeMap() 和 addPointToMap() 函数,但是在不实际发出 http 请求来获取所需的 API 模块并创建我需要的每个类的具体实例的情况下,最好的方法是什么?一个测试类可能如下所示:

describe('MapComponent', () => {
let fixture: ComponentFixture<MapComponent>;
let component;

beforeEach(async () => {
 TestBed.configureTestingModule({
  declarations: [MapComponent],
}).compileComponents();
 
fixture = TestBed.createComponent(MapComponent);
component = fixture.debugElement.componentInstance;
});

it('should initialize map', async () => {
 // calling this function will fetch the ArcGIS JS API dependencies
// and create concrete instances of Map and MapView objects - need
// to mock these      
await component.initializeMap();
expect(component.mapService.mapView).toBeTruthy();
});

it('should add a point to the map', async () => {
await component.addPointToMap(32.7, -117.1);
// assert point is created in component.mapService.mapView object
   });
 });

标签: angulararcgisesriarcgis-js-api

解决方案


Esri 社区帖子中的一位用户很好地回答了这个问题。链接在这里:

https://community.esri.com/t5/arcgis-api-for-javascript/angular-developers-how-are-you-unit-testing-classes-which/mp/1006825

这个想法是使用将 Arcgis 相关代码包装到一个包装器中,并使用第三方库Typemoq创建模拟对象并将它们传入和传出以验证功能。

这是一个有点老的问题,但如果他们是使用 Arcgis 测试模块的新手,它将对他们有所帮助。


推荐阅读