我遇到以下源代码和相应的单元测试问题:
来源:
public laufeVorwaertsUndZurueck(laenge:number):ng.IPromise<any>{
return this.ev3DifferentialPilotAdapterService.run(laenge)
.then((response:any)=> {
return this.ev3DifferentialPilotAdapterService.rotate(180);
})
.then((response:any)=> {
return this.ev3DifferentialPilotAdapterService.run(laenge);
})
.then((response:any)=> {
return this.ev3DifferentialPilotAdapterService.rotate(180);
});
console.log("done");
}
单元测试:
it("laufe 60cm vorwärts und laufe wieder zurück", () =>{
var promise = qService.resolve("resolved");
console.log(promise);
spyOn(ev3DifferentialPilotAdapterService, "run").and.returnValue(promise);
spyOn(ev3DifferentialPilotAdapterService, "rotate").and.returnValue(promise);
baseBallAktionenService.laufeVorwaertsUndZurueck(60);
expect(ev3DifferentialPilotAdapterService.run).toHaveBeenCalledWith(60);
expect(ev3DifferentialPilotAdapterService.run).toHaveBeenCalledTimes(2);
expect(ev3DifferentialPilotAdapterService.rotate).toHaveBeenCalledWith(180);
expect(ev3DifferentialPilotAdapterService.rotate).toHaveBeenCalledTimes(2);
})
即使很难通过已解决的 promise对象,也永远不会调用 .then 方法中的Callback-Functions。正常运行时Source很好,但是使用jasmine的 spyOn 在Unit测试中执行时表现错误。
答案 0 :(得分:3)
解决承诺后使用$ digest。
见下文..
it("laufe 60cm vorwärts und laufe wieder zurück", () =>{
spyOn(ev3DifferentialPilotAdapterService, "run").and.returnValue(promise);
spyOn(ev3DifferentialPilotAdapterService, "rotate").and.returnValue(promise);
baseBallAktionenService.laufeVorwaertsUndZurueck(60);
var promise = qService.resolve("resolved");
$scope.$digest();
expect(ev3DifferentialPilotAdapterService.run).toHaveBeenCalledWith(60);
expect(ev3DifferentialPilotAdapterService.run).toHaveBeenCalledTimes(2);
expect(ev3DifferentialPilotAdapterService.rotate).toHaveBeenCalledWith(180);
expect(ev3DifferentialPilotAdapterService.rotate).toHaveBeenCalledTimes(2);
})