将复杂操作移到服务中,并在构造函数中注入服务以进行测试。
举例来说,假设我们有一个组件需要根据经纬度获取位置名称并显示在页面上。我们可以将获取位置名称的逻辑移动到一个位置服务中,并注入到组件中以便以后进行测试。
位置服务代码:
export class LocationService{
private geocoder: google.maps.Geocoder;
constructor() {
this.geocoder = new google.maps.Geocoder();
}
public async getLocationName(lat: number, long: number): Promise {
return new Promise((resolve, reject) => {
const location = new google.maps.LatLng(lat, long);
this.geocoder.geocode({ location }, (results, status) => {
if (status === google.maps.GeocoderStatus.OK && results[0]) {
// Return the first result
resolve(results[0].formatted_address);
} else {
reject(`Could not get location name. Error: ${status}`);
}
});
});
}
}
组件代码:
export class LocationComponent implements OnInit {
public locationName: string;
constructor(private locationService: LocationService) {
this.locationName = '';
}
async ngOnInit() {
const lat = 40.748817;
const long = -73.985428;
// This will call the location service to get the location name
this.locationName = await this.locationService.getLocationName(lat, long);
}
}
现在我们可以轻松地为位置服务编写单元测试而无需处理复杂的Angular构造函数。