【发布时间】:2021-01-01 16:50:31
【问题描述】:
我正在尝试对我的组件运行单元测试。
component.ts:
async ngOnInit(): Promise<void> {
await this.dataProviderService.getCurrencyCodesList().then(data => {
this.currencyList = data;
});
this.currencyList.sort((a, b) => {
return a.code > b.code ? 1 : -1;
});
// ...
}
使用的服务方法:
async getCurrencyCodesList(): Promise<any[]> {
// ...
const currencyCodes = currencyList.map(data => {
return {code: data.code, currency: data.currency, table: data.table};
});
return currencyCodes;
}
在 spec.ts 文件中我尝试创建一个存根
//...
it('should have currencies in the list', () => {
expect(component.currencyList.length).toBeGreaterThan(1);
});
});
class DataProviderServiceStub {
async getCurrencyCodesList(): Promise<Observable<any[]>> {
return of ([{code: 'PLN', table: 'A'},
{code: 'EUR', table: 'A'}]);
}
}
// then this:
class DataProviderServiceStub {
async getCurrencyCodesList(): Promise<any[]> {
return ([{code: 'PLN', table: 'none'},
{code: 'EUR', table: 'A'}]);
}
}
//also tried return (of)([]), ([{}]) etc.
问题是我在从存根得到的数组上使用 .sort 时遇到了这样的 Karma 错误:
Error: Uncaught (in promise): TypeError: this.currencyList.sort is not a function
TypeError: this.currencyList.sort is not a function
有时显示为错误,有时显示为 AfterAll 错误,有时显示一切正常。我做错了什么?
测试结果失败:“TypeError: Cannot read property 'length' of undefined”
【问题讨论】:
标签: angular unit-testing karma-jasmine angular-test