单元测试和角度未处理的 Promise 拒绝

Mar*_*del 5 jasmine angular

我目前在使用带有承诺的茉莉花测试时遇到问题。

错误是“未处理的承诺拒绝:”这意味着我的承诺没有正确处理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();
    });
  });
Run Code Online (Sandbox Code Playgroud)

在函数中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);
          });
Run Code Online (Sandbox Code Playgroud)

...调用该函数:

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

reject()似乎setPath是问题所在,因为另一个测试进行得resolve()很好

欢迎任何帮助

Anu*_*ige 2

你有Promise,resolvereject方法setPath。使用第二个参数回调代替子句,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);
              });
Run Code Online (Sandbox Code Playgroud)

阅读这篇文章