Search code examples
angularunit-testingkarma-jasmine

I can't reach the component from the spec file in Angular - Karma/Jasmine unit tests


I'm trying to run a simple unit test in Angular, but it's failing, I can't access the component from the spect file. it says that can't find property of undefined, I can't figure out where's the mistake.this is the function in the component that I'm trying to test:

factorOrQuickpay(): void {
    if (this.load.factor) {
        this.factor = true;
        this.resourceType = TableResources.Factor;
    } else if (!this.load.factor) {
        this.factor = false;
        this.resourceType = TableResources.Quickpay;
    } else if(!this.load.factor && !this.load.quickpay) {
        this.none = true;
    }
}

and this is the .spec file:

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { LoadResourcesComponent } from './load-resources.component';

describe('LoadResourcesComponent', () => {
    let component: LoadResourcesComponent;
    let fixture: ComponentFixture<LoadResourcesComponent>;

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            declarations: [LoadResourcesComponent],
        }).compileComponents();
    });

    beforeEach(() => {
        fixture = TestBed.createComponent(LoadResourcesComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    fdescribe('factorOrQuickpay', () => {
        beforeEach(() => {
            spyOn(component, 'factorOrQuickpay');
        });

        it('shows Factor Load scenario', () => {
            component.factorOrQuickpay()
            expect(component.factor).toBe(true);
        });
    });
});

Where is the error?

The error message is "TypeError: Cannot read property 'factor' of undefined".


Solution

  • I think your node version is 15.0. downgrading your node version to node 14.0 will work.

    refer this: https://github.com/karma-runner/karma/issues/3571