angular - '未处理的 Promise 拒绝 :', ' 无法读取未定义的属性(读取 'then' )'

标签 angular typescript karma-jasmine

我有这个错误:

'Unhandled Promise rejection:', 'Cannot read properties of undefined (reading 'then')', '; Zone:', 'ProxyZone', '; Task:', 'jasmine.onComplete', '; Value:', TypeError: Cannot read properties of undefined (reading 'then')
TypeError: Cannot read properties of undefined (reading 'then')

这是我的 .ts 文件:

getPillars = async (): Promise<void> => {

        if (localStorage.getItem('pillars')) {
            this.pillars = JSON.parse(localStorage.getItem('pillars'));
            return;
        }

        let items = await this.api.send('Categories', 'get', filter ? { filter: filter } : {}).then((res: { data: any[], count: number }) => {
            return res.data.map(el => {
                return { id: el.id, name: el.name, type: 'Categories' }
            });
        });
        localStorage.setItem('pillars', JSON.stringify(items));

        this.pillars = items;
    }

还有我的测试文件:

describe('getPillars()', () => {
    it('Should validate the session success', () => {
        let spy1 = spyOn(apiService, 'send').and.returnValue(Promise.resolve(of('pillars')));

        component.getPillars();

        expect(spy1).toHaveBeenCalled();
      });
  });

最佳答案

let items = await this.api.send('Categories', 'get', filter ? { filter: filter } : {}).then((res: { data: any[], count: number }) => {
            return res.data.map(el => {
                return { id: el.id, name: el.name, type: 'Categories' }
            });
        });

在这里等待发送返回的 promise

但在稍后的测试中,您返回的 promise 会解析为另一个 promise 。

您必须使其解析为某个实际值

let spy1 = spyOn(apiService, 'send').and.returnValue(Promise.resolve('pillars'));

关于angular - '未处理的 Promise 拒绝 :', ' 无法读取未定义的属性(读取 'then' )',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68957034/

相关文章:

node.js - 带有 Webpack、Typescript 和 ES6 的 elastic-apm-node 不工作?

javascript - Nest 无法解析对导出服务的依赖关系

typescript - 返回列表大小的通用函数中的 no-explicit-any

AngularJS/Karma 测试 : beforeEach not executed

unit-testing - 如何使用 Angular 2 中的日期管道测试元素的呈现?

Angular Testing 模块和覆盖

angular - Angular 是否有标签输入组件?

html - 如何使用 rel ="preload"和 Angular 的哈希文件名预加载内容?

javascript - 如何检查元素是否以 Angular 2渲染

angular 2 应用程序未加载,但我没有收到任何错误