属性在规范文件中被认为是未定义的,即使它存在于组件中.用Karma - Jasmine在Angular中进行单元测试.&



我在Angular的一个组件中有以下方法,但是当我为它编写单元测试时,它失败了,不能识别组件中实际存在的属性;这是我的方法

makeUrl(): string {
const base: string = this.marketConditionsEnvironment.apiRoot;
const tempEquipment: string = '?equipment=Van';
const origin: string = this.makeLocation('origin', this.marketConditionsData.origin); 
const searchCriteria: CreateSearchCriteria = this.dataSource.currentCriteria.createAndExecuteSearchCriteria.searchCriteria;
if (searchCriteria.origin?.point) {
return `${base}${tempEquipment}${origin}`;
}
return `${base}${tempEquipment}`;
}

我为它写了这个单元测试:

describe('makeUrl', () => {
it('should call initCapital and makeLocation', () => {
spyOn(component, 'initCapital');
spyOn(component, 'makeLocation');
component.makeUrl();
expect(component.initCapital).toHaveBeenCalled();
expect(component.makeLocation).toHaveBeenCalled();
});
});

但是,测试失败,出现以下错误:"TypeError: Cannot read properties of undefined (reading 'currentCriteria')"

它无法到达"数据源"。对象。

通过输入传递给组件:

@Input() dataSource: LoadsDataSource;

我做错了什么?谢谢你。

当您编写测试时,没有任何东西被自己初始化。你的测试似乎很标准,所以问题一定是你没有初始化dataSource属性内的测试(它是输入是不相关的,同样适用于"常规";属性)

相关内容