Home > OS >  Property recognized as undefined in spec file even though it exist in the component. Unit Test in An
Property recognized as undefined in spec file even though it exist in the component. Unit Test in An

Time:09-22

I have the following method in a component in Angular but when I wrote the unit test for it, it fails, does not recognize properties that actually exists in the component; this is my method

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}`;
}

And I wrote this unit test for it:

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

However, the test fails with the following error: "TypeError: Cannot read properties of undefined (reading 'currentCriteria')".

It can't reach the "dataSource" object.

It is being passed via input to the component:

@Input() dataSource: LoadsDataSource;

What am I doing wrong? Thank you.

CodePudding user response:

When you write a test nothing gets initialized by itself.. your test seems pretty standard, so the problem must be you not initializing dataSource property inside test (it being Input is irrelevant, the same goes for "regular" properties)

  • Related