我有这个错误:
'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/