0

我有一个异步方法,我正在调用其他 2 个返回承诺的方法。我在嘲笑uploadDataaddOrEdit返回一个已解决的承诺。当我调用 时uploadFileuploadDataaddOrEdit方法都被覆盖了,但是期望,即被addOrEdit调用失败。我正在使用带有 Jest 的 Angular 9。

这是代码:

待测方法:

 async uploadFile(): Promise<void> {
    
      let uploadedLeis: Lei[] = [];
      this.onNoClick(); // closeing the upload dialog
    
      try {
        const { leis, errors } = await this._fileService.uploadData(
          this.files[0],
        );
    
        try {
          uploadedLeis = await this._lei.addOrEdit(leis);
    
          if (!this._util.isEmpty(uploadedLeis)) {
            this._lei.updateLocalData(uploadedLeis);
    
            if (this._util.isEmpty(errors)) {
              this._notification.notifySuccess(
                `File was successfully uploaded with ${uploadedLeis.length} LEI(s)`,
              );
            } else {
              this._notification.notifySuccess(
                `File was successfully uploaded with ${uploadedLeis.length} LEI(s).\nThere were ${errors.length} errors in the file`,
                'View Errors',
              );
            }
          } else {
            this._notification.notifyError(`No records were updated`);
          }
        } catch (err) {
          this._notification.notifyError(
            `Sorry!! Failed to update records from the file`,
            err,
          );
        }
      } catch (err) {
        this._notification.notifyError(
          `Sorry!! Problem occured while reading the file\n${err.error}`,
          err,
        );
      } finally {
        this.files = [];
      }
    }

测试用例

it(`test description`, fakeAsync(() => {
  const spy1 = jest.spyOn(component, 'onNoClick');
  const spy2 = jest.spyOn(fileService, 'uploadData').mockResolvedValue({
    leis: [],
    errors: [],
  });
  const spy3 = jest.spyOn(leiService, "addOrEdit").mockResolvedValue({});

  component.fileUploaded = true;
  component.files = event;

  fixture.detectChanges();

  component.uploadFile();

  flush();
  expect(spy1).toBeCalled();     // passes
  expect(spy2).toBeCalled();    // passes
  expect(spy3).toBeCalled();   // fails
}));
4

1 回答 1

0

在继续你的断言之前尝试使用tickflushMicrotasks解决承诺。我认为flush()只转发时间而不是承诺。可以flushMicrotasks用 just替换所有内容,tick但我不确定。

像这样的东西:

import { flushMicrotasks } from '@angular/core/testing';


it(`test description`, fakeAsync(() => {
  const spy1 = jest.spyOn(component, 'onNoClick');
  const spy2 = jest.spyOn(fileService, 'uploadData').mockResolvedValue({
    leis: [],
    errors: [],
  });
  const spy3 = jest.spyOn(leiService, "addOrEdit").mockResolvedValue({});

  component.fileUploaded = true;
  component.files = event;

  fixture.detectChanges();

  component.uploadFile();

  flushMicrotasks();
  expect(spy1).toBeCalled();     // passes
  flushMicrotasks();
  expect(spy2).toBeCalled();    // passes
  flushMicrotasks();
  expect(spy3).toBeCalled();   // fails
}))
于 2020-06-29T20:26:56.143 回答