角度jamine / karma测试承诺功能

时间:2017-12-19 00:10:33

标签: angular jasmine karma-runner karma-jasmine

我试图在以下函数中测试promse函数

loadDetail(id) {
    this.bookingService.getServices(id).then((ret) => {
        if (ret.result) {
            this.sevices = ret.payload;
        } 
    }).catch((error) => {});       
}

我的测试是:

it('loadDetail successfully return services.', inject(
    [BookingService], (service: BookingService) => {
        service.initBooking();

        let ret = new returnObj();
        ret.result = true;
        ret.payload = new Array<any>();
        ret.payload.push({id: 1, title: "Title 1"});
        ret.payload.push({id: 2, title: "Title 2"});
        ret.payload.push({id: 3, title: "Title 3"});

        const spy = spyOn(service, "getServices").and.returnValue(Promise.resolve(ret));

        component.loadDetail(1);

        expect(component.sevices.length).toEqual(3);
    }
));

当我运行测试时,我得到错误&#34;预期0等于3。&#34; 我在这做错了什么?我已经按照例子说明了,我非常确定我正确使用了间谍。

1 个答案:

答案 0 :(得分:1)

问题是promises是异步的,结果在loadDetail(1)完成之前被声明。

为了进行有效测试,异步函数应始终返回promise或observable:

loadDetail(id) {
  return this.bookingService.getServices(id)....
}

如果它不应该返回结果,那么它将是undefined的承诺。

这种方式可以链接。这对async..awaitasyncfakeAsync Angular助手特别有用:

it('loadDetail successfully return services.', fakeAsync(inject(
    [BookingService], async (service: BookingService) => {
        ...
        const spy = spyOn(service, "getServices").and.returnValue(Promise.resolve(ret));

        await component.loadDetail(1);

        expect(component.sevices.length).toEqual(3);
    }
));

这也可以通过fakeAsynctick帮助程序来解决,以同步方式测试异步代码(这不会像真正的HTTP请求那样真正的异步操作):

it('loadDetail successfully return services.', fakeAsync(inject(
    [BookingService], (service: BookingService) => {
        ...
        const spy = spyOn(service, "getServices").and.returnValue(Promise.resolve(ret));

        component.loadDetail(1);
        tick(0); // promise chain was executed

        expect(component.sevices.length).toEqual(3);
    }
));