我在我的Angular应用程序中有一个GeoLocationService
,如下所示。
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
@Injectable()
export class GeoLocationService {
coordinates: any;
constructor() {}
public getPosition(): Observable<Position> {
return Observable.create(observer => {
navigator.geolocation.watchPosition((pos: Position) => {
observer.next(pos);
}),
() => {
console.log("Position is not available");
},
{
enableHighAccuracy: true
};
});
}
}
我想对这个服务进行单元测试,以确保getPosition()
函数返回一个可用的Observable
。以下是我的测试代码。
import { TestBed, fakeAsync } from "@angular/core/testing";
import { GeoLocationService } from "./geo-location.service";
import { take } from "rxjs/operators";
describe("GeoLocationService", () => {
let service: GeoLocationService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [GeoLocationService]
});
service = TestBed.get(GeoLocationService);
});
it("should get observable value", fakeAsync((done: DoneFn) => {
service
.getPosition()
.subscribe(value => {
expect(value.coords).not.toBeUndefined();
expect(value.coords).not.toBeNaN();
expect(value.coords).not.toBeNull();
done();
});
}));
});
这里发生的情况是,一旦我运行测试,测试成功了(这是因为测试中的
subscribe
块尚未运行)。在打开的Chrome浏览器窗口
上(用于在karma中查看测试结果),我选择Allow
,以使应用程序找到我的位置,在此时subscribe
块就会运行,但由于此时it
规范已经完成,因此我会收到一个console error
。
Uncaught Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out
。(“expect”被使用时没有当前规范,这可能是因为异步测试超时)。
我不知道执行这个测试的推荐方法是什么。
done
回调了。 - Ander2