刷新Angular HTTP TestRequest序列



我有一个async函数,它需要发出POST请求,但必须首先从服务器获取一些数据:

async createObject() {
// HTTP request #1: dep1 is needed for the second request
const dep1 = await this.http.get("/urlA")
.pipe(first())
.toPromise();
// Create the request object out of dep1 and some additional values
const req = mkCreateParams(this.name, dep1);
// HTTP request #2: Build something
const res = await this.http.post("/urlB")
.pipe(first())
.toPromise();
// When everything is done: Navigate away
this.router.navigateByUrl(`/urlC/${res.id}`);
return res;
}

我使用以下代码来测试这个:

const httpTesting = TestBed.inject(HttpTestingController);
const req = testInstance.createObject();
httpTesting
.expectOne("/urlA")
.flush({ /* ... SNIP ... */);
const generatedId = "f9f64792-0ceb-4e3c-ae7b-4c7a8af6a552";
httpTesting
.expectOne({ method: "POST", url: "/urlB" })
.flush({ id: generatedId });
const res = await req;
expect(res.id).toEqual(generatedId);

当期望/urlB时,这会立即失败,甚至没有到达解析res的行。错误消息如下:

Expected one matching request for criteria "Match method: POST, URL: /urlB", found none.

这似乎是因为在调用HttpTestingController.expectOne()时一定已经发出了请求。由于承诺在JavaScript中得到了热切的解决,第一个请求已经发出,但第二个请求没有发出。

有没有办法告诉AngularHttpTestingController放松一点,等待一段时间后的请求?HttpTestingController.verify的存在暗示了这一点,但我不知道如何进入有用的状态。

我认为等待承诺可以帮助你,试试fixture.whenStable()

it('your title here', async done => {
const httpTesting = TestBed.inject(HttpTestingController);
const req = testInstance.createObject();
httpTesting
.expectOne("/urlA")
.flush({ /* ... SNIP ... */);
await fixture.whenStable(); // wait for the pending promises to resolve before proceeding
const generatedId = "f9f64792-0ceb-4e3c-ae7b-4c7a8af6a552";
httpTesting
.expectOne({ method: "POST", url: "/urlB" })
.flush({ id: generatedId });
await fixture.whenStable(); // wait for the pending promises to resolve before proceeding
const res = await req;
expect(res.id).toEqual(generatedId);
// call done to let Jasmine know you're done with this test
done();
});

最新更新