【问题标题】:Mocking getCurrentPosition with Jasmine and TypeScript用 Jasmine 和 TypeScript 模拟 getCurrentPosition
【发布时间】:2021-10-18 16:34:45
【问题描述】:

我正在尝试使用 Jasmine 对 Angular2 组件 (TypeScript) 中的 navigator.geolocation.getCurrentPosition 方法的“承诺”版本进行单元测试:

async getCurrentPosition() {
    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 });
    });
  }

我的测试(不相关的组件实例化除外)如下所示:

fit('should GEOLOCALIZE the BROWSER', async () => {
    const position = { coords: { latitude: 0, longitude: 0 } };
    const mockGeolocation: jasmine.SpyObj<Geolocation> = jasmine.createSpyObj('navigator.geolocation', ['getCurrentPosition']);
    mockGeolocation.getCurrentPosition.and.callFake(() => {
      return { then: () => position };
    });
    await component.getCurrentPosition();
    expect(navigator.geolocation.getCurrentPosition).toHaveBeenCalled();
  });

但我无法通过测试,模拟的地理位置似乎没有效果,5000ms 超时触发,取消了地理位置,测试失败:

Chrome Headless 92.0.4515.131 (Windows 10): Executed 1 of 273 (1 FAILED) (skipped 272) (0.402 secs / 0.113 secs)
TOTAL: 1 FAILED, 0 SUCCESS


1) should GEOLOCALIZE the BROWSER
     LoginComponent
     User denied Geolocation

我看到 other posts 声称这样的事情会起作用:

spyOn(navigator.geolocation,'getCurrentPosition').and.callFake(function(locationSuccess, locationError) {
    const position = { coords: { latitude: 32, longitude: -96 } };
    arguments[0](position);
  });

但显然,由于 TypeScript 的严格性,我不能在这里使用 arguments 保留关键字。有其他选择吗?

知道我做错了什么吗?

提前致谢。

【问题讨论】:

    标签: angular typescript testing jasmine geolocation


    【解决方案1】:

    实际上,深入研究TypeScript documentation,我发现实际上有一个TypeScript 替代经典的arguments 变量,省略号语法:

    function multiply(n: number, ...m: number[]) {
      return m.map((x) => n * x);
    }
    

    这确实提供了预期的结果:

    spyOn(navigator.geolocation, 'getCurrentPosition').and.callFake((...args: any[]) => {
          const position = { coords: { latitude: 0, longitude: 0 } };
          args[0](position);
        });
    

    现在测试通过了:

    LoginComponent
        √ should GEOLOCALIZE the BROWSER
    
    Chrome Headless 92.0.4515.131 (Windows 10): Executed 1 of 274 (skipped 273) SUCCESS (0.559 secs / 0.281 secs)
    TOTAL: 1 SUCCESS
    

    愿此信息对其他人有所帮助!

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 2011-10-21
      • 1970-01-01
      • 2021-10-30
      • 2013-12-20
      • 1970-01-01
      相关资源
      最近更新 更多