angular - 单元测试和 Angular 未处理的 promise 拒绝

标签 angular jasmine

我目前在使用带有 promise 的 Jasmine 测试时遇到问题。

错误是“Unhandled Promise rejection:”,我想这意味着我的 promise 没有正确处理 catch()then()

这是我的测试:

it('tests the openRepo function with changed and invalid path', (done) => {
    const OldPath = '/old';
    const NewPath = '/invalid';
    const ProjectModalBoolean = true;
    component.path = OldPath;
    component.openFolder = NewPath;
    component.projectModalLoading = ProjectModalBoolean;
    component.openRepo().then(() => {
      expect(component.openFolder).toBe('');
      expect(component.projectModalLoading).toBeFalsy();
      done();
    });
  });

在函数 openRepo 中,我有以下代码:

return this.gitService.setPath(this.openFolder)
          .then((data) => {
            this.projectModalLoading = false;
            this.projectModalVisible = false;
            this.openFolder = '';
            this.toastr.info(data.message, data.title);
          })
          .catch((data) => {
            this.projectModalLoading = false;
            this.openFolder = '';
            this.toastr.error(data.message, data.title);
          });

...调用函数:

async setPath(newPath) {
        new Promise<ServiceResult>((resolve, reject) => {
            if (newPath === '/new') {
                resolve(new Object());
            } else {
                reject(new Object());
            }
    });
}

setPath 中的 reject() 似乎是问题所在,因为另一个通过 resolve() 的测试工作得很好

欢迎任何帮助

最佳答案

您在 setPath 方法上有 Promiseresolvereject。而不是 catch 子句使用第二个参数回调,如下所示。

    return this.gitService.setPath(this.openFolder)
              .then((data) => {
                this.projectModalLoading = false;
                this.projectModalVisible = false;
                this.openFolder = '';
                this.toastr.info(data.message, data.title);
              },
              (data) => {
                this.projectModalLoading = false;
                this.openFolder = '';
                this.toastr.error(data.message, data.title);
              });

阅读此 article

关于angular - 单元测试和 Angular 未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54858341/

相关文章:

angular - 路由中的canActivate和canDeactivate是什么?

javascript - Jasmine 测试在值为 null 时调用函数

javascript - 保存 jasmine Expect() 结果

javascript - 使用 Karma 读取静态文件

javascript - 使用 Angular 登录谷歌

angular - 错误: Invalid provider for the NgModule 'AppModule' - only instances of Provider and Type are allowed

Angular2 RC5 错误 :zone. js:未处理的 Promise 拒绝:没有 ElementRef 的提供者

unit-testing - Angular 2 + Jasmine - 测试元素是否可见

javascript - Angular - 使用 jasmine 测试 websocket 包装器

javascript - 尝试使用 jasmine 和 angular 时出错