Angular构造函数中复杂的位置难以测试。
创始人
2024-10-26 12:02:09
0

将复杂操作移到服务中,并在构造函数中注入服务以进行测试。

举例来说,假设我们有一个组件需要根据经纬度获取位置名称并显示在页面上。我们可以将获取位置名称的逻辑移动到一个位置服务中,并注入到组件中以便以后进行测试。

位置服务代码:

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构造函数。

相关内容

热门资讯

热点推荐!hhpoker免费透... 热点推荐!hhpoker免费透视脚本,aapoker安装包怎么使用,总是是有挂(真的有挂)1、下载好...
大神推荐!哈糖大菠萝软件下载,... 大神推荐!哈糖大菠萝软件下载,we poker游戏下,总是是有挂(有挂细节)1、上手简单,内置详细流...
一分钟教你!aa poker辅... 一分钟教你!aa poker辅助包,pokeplus脚本,好像真的是有挂(有挂讲解);1、完成辅助器...
来一盘!wepoker的辅助器... 来一盘!wepoker的辅助器,wpk透视工作室,真是存在有挂(揭秘有挂)1、玩家可以在线上大神俱乐...
科技分享!pokermaste... 科技分享!pokermaster修改器,wepoker游戏安装教程,其实真的是有挂(有挂规律)1、操...
一分钟了解!德普之星辅助工具如... 一分钟了解!德普之星辅助工具如何打开,wepoker免费脚本,都是是真的有挂(有挂讲解);1、wep...
实测分享!wepokerplu... 实测分享!wepokerplus脚本,aapoker怎么选牌,原来真的是有挂(有挂教学)1、这是跨平...
玩家必备教程!hhpoker可... 玩家必备教程!hhpoker可以控制牌吗,德州局透视脚本,一直存在有挂(有挂技巧)1、让任何用户在无...
如何分辨真伪!wepoker有... 如何分辨真伪!wepoker有辅助吗,hhpoker是真的还是假的,竟然有挂(有挂解惑)1、任何透视...
避坑细节!wepoker透视a... 避坑细节!wepoker透视app下载,HH平台挂,果然是真的有挂(证实有挂)亲,关键说明,透视脚本...