使用Jest无法在Angular中测试异步(Promise)代码

时间:2020-06-24 16:50:15

标签: angular unit-testing promise angular-jest asynctest

我正在尝试使用玩笑角度测试异步代码。它无法按应有的方式测试已解决和被拒绝的承诺。 这是我正在测试的代码。 (角材料数据表)

method.ts

openAddOrEditDialog(category: AvtType, typesData?: TypeAvt): void {
    const dialogRef = this._dialog.open(AddOrEditAvtComponent, {
      disableClose: true,
      id: 'addOrEditAvt',
      width: '30%',
      height: '25%',
      data: {
        title: typesData ? 'Edit Type' : 'Add New Type',
        typesData,
        category,
      },
    });
    this.editSubscription = dialogRef
      .afterClosed()
      .subscribe((modifiedTypes: TypeAvt[]) => {
        if (modifiedTypes) {
          this._typesAvt.addOrEdit(modifiedTypes)
            .then((types: TypeAvt[]) => {
              if (!this._util.isEmpty(types)) {
                this._typesAvt.updateLocalData(types);
                this._notificationService.notifySuccess('Type was successfully updated');
                console.log('I am in then');
              }
            })
            .catch((err: HttpError) => {
              this._notificationService.notifyError('Sorry!! Failed to update the Type', err);
            });
        }
      });
  }

test.spec.ts

it(`should display 3 AVT Types in the data table when the add button is clicked and the data is entered in the popup`, fakeAsync(() => {
  const spy = jest.spyOn(notificationService, 'notifySuccess');
  jest.spyOn(typesAvtService, 'addOrEdit').mockResolvedValue([newType]);
  const addBtn: HTMLElement = fixture.debugElement.query(By.css('.btn--add'),).nativeElement;

  addBtn.click();  /* invokes openAddOrEditDialog method */
  flush();
  //tick();
  //flushMicrotasks();
  expect(spy).toBeCalled();
  console.log('I am after expect');
}));
    

我使用console.log语句跟踪执行顺序。该测试失败。 'I am after expect''I am in then'之前被打印。

我要去哪里错了?

0 个答案:

没有答案
相关问题