Angular4:如何模拟顺序调用的2个http调用的返回值

时间:2018-10-09 16:39:05

标签: angular

我有一个函数,可以进行2个连续的HTTP调用-根据第一个调用的结果进行第二个调用。单元测试时如何正确模拟两个调用?

component.ts

getValue(): Promise<any[]> {
    return this.http.get(URL1).toPromise()   // FIRST CALL
        .then(data => {
            this.enable = data.json()['enable'];
        })
        .then(() => {
            if (this.enable) {
                return new Promise<any[]>((resolve) => {
                    this.http.get(URL2).toPromise()  // SECOND CALL
                        .then(res => res.json()));
                });
            }
        })
        .catch(() => {
            return new Promise<any[]>((resolve) => resolve([]));
        });
}

component.spec.ts

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [HttpModule],
        providers: [...]
    });
    service = TestBed.get(...);
    http = TestBed.get(Http);
});

it('getValue works as expected when call succeeds',() => {
    spyOn(http, 'get').and.returnValue(of({enable: true}));  // return of firstcall
    spyOn(http, 'get').and.returnValue(of(RAW_DATA));  // return of second call
    service.getValue ('uuid')
        .then(data => {
            expect(data).toEqual(expectedData);
        });
});

1 个答案:

答案 0 :(得分:0)

这应该返回给第一个调用提供的第一个值,为第二个调用提供第二个值。

spyOn(http, 'get').and.returnValues(of({enable: true}), of(RAW_DATA));