【发布时间】: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
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