首页 > 解决方案 > '未处理的承诺拒绝:','无法读取未定义的属性(读取'then')'

问题描述

我有这个错误:

'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();
      });
  });

标签: angulartypescriptkarma-jasmine

解决方案


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' }
            });
        });

在这里,您等待从发送返回的承诺

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

您必须使它只是解析为一些实际值

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

推荐阅读