等待单元测试Angular中的可观察内部方法



我有以下代码:

app.component.specs.ts:

it('should upload files and add links to array', async () => {
const files = new TestFileList() as any as FileList;
component.uploadFiles(files);
await new Promise((resolve => setTimeout(resolve, 5000)));
expect(component.photoUrls.length).toEqual(files.length);
});
}

app.component.ts

uploadFiles(files: FileList) {
for (let i = 0; i < files.length; i++) {
this.photoService.uploadPhoto(files.item(i)).subscribe(data => this.photoUrls.push(data.link), error => alert(error));
}
}

在app.component.specs.ts中承诺超时看起来不太好。我该如何等待,直到所有文件都被上传,并以其他方式将链接添加到数组中?

这很有趣,我还没有处理过这样的情况。但通常,我会重用一个名为waitUntil的实用函数。

import { interval } from 'rxjs';
.....
export const waitUntil = async (untilTruthy: Function): Promise<boolean> => {
while (!untilTruthy()) {
await interval(25).pipe(take(1)).toPromise();
}
return Promise.resolve(true);
};

你可以随意设置时间,我只是默认为25毫秒。

it('should upload files and add links to array', async (done) => {
const files = new TestFileList() as any as FileList;
component.uploadFiles(files);
await waitUntil(() => component.photoUrls.length === files.length);
// you may not have to do the following assertion because we waited for it to be true
expect(component.photoUrls.length).toEqual(files.length);
done();
});

通过这种方式,我们不依赖于时间(setTimeOut of 5s(,但我们只是保持循环,直到条件变得真实,然后继续我们的断言。我觉得这个读起来更好。

请这样尝试。如果不起作用,请告诉我?

it('should upload files and add links to array' , inject([PhotoService] , fakeAsync((photoService : PhotoService) => {
const files = new TestFileList() as any as FileList;
spyOn(photoService ,'uploadPhoto').and.returnValue(of('http://image1.jpeg'));
component.uploadFiles(files);
tick(3000);
expect(component.photoUrls.length).toEqual(files.length);
})));

最新更新