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

时间:2020-03-11 19:03:16

标签: angular unit-testing jasmine karma-jasmine

我有以下代码:

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中承诺超时看起来不太好。我该如何等待所有文件上传完毕并以其他方式将链接添加到阵列上?

2 个答案:

答案 0 :(得分:1)

请尝试这样。让我知道它是否无效?

 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);
  })));

答案 1 :(得分:1)

这很有趣,我还没有处理这样的情况。但是通常,我会重复使用名为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);
};

您可以将时间设置为任意时间,我默认将其设置为25ms。

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),而只是不断循环直到条件变为真,然后继续我们的断言。我认为这样读起来更好。