Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Karma-Jasmine: TypeError: Cannot read properties of undefined (reading 'get')

I am trying to write a unit test for my angular component and I am stuck at this error. I have researched a lot about this on stack overflow and some online docs. Here is the link of resources which I have tried so far with no luck.

  • How to ActivatedRoute in Angular and how to mock it in Unit Tests
  • How to unit test a component that depends on parameters from ActivatedRoute?
  • How do you mock ActivatedRoute

Below is my code

.ts file

export class SomeComponent implements OnInit {
  id = '--';
  
  constructor(
    private readonly someService: SomeService,
    private readonly utilsService: UtilsService,
    private readonly router: Router,
    readonly route: ActivatedRoute,
  ) {}

  ngOnInit() {
    this.id = this.route.snapshot.queryParamMap.get('id');
    this.getDetails();
  }

  viewInventory(){
    this.router.navigate(['..'], {
      relativeTo: this.route
    });
  }

  getDetails() {
    if (this.id) {
      this.getResourceOverview();
    }
  }

  getResourceOverview(): void {
    const resourceID = `search_keys=${"resource_id"}&search=${this.id}`
    this.resourceId = this.id
    this.someService
      .getResourceOverview(resourceID)
      .subscribe(
        (response) => {
          const result = response as any;
          if (result && something) {
            this.id = something  || '--';
          }
        },
        (error) => {
          console.log('Resource overview details failed with error', error);
        }
      );
  }
}

.ts.spec

class mockHttpWrapperService {
  readonly isApiReady = false;
}

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

  beforeEach(async(() => {
    activatedRouteSpy = {
      snapshot: {
        paramMap: convertToParamMap({
          id: 'dads123',
          code: 'IBM',
        })
      }
    };
    TestBed.configureTestingModule({
      declarations: [SomeComponent],
      imports: [
        SomeLibModule, CarbonModule, SomeModule.forRoot(),
        RouterModule.forRoot([])
      ],
      providers: [
        { provide: NGXLogger, useClass: MockNGXLogger },
        { provide: HttpWrapperService, useClass: mockHttpWrapperService },
        { provide: Router, useClass: class { navigate = jasmine.createSpy("navigate"); }},
        ApiContractService,
        TranslationService,
        ApiService,
        ApiContractService,
        TranslationService,
        SomeService,
        {
         provide: ActivatedRoute,
         useValue: activatedRouteSpy
        }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })
    .compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(SomeComponent);
      component = fixture.debugElement.componentInstance;
      fixture.detectChanges();
      component.ngOnInit();
    })
  }));

  it('should create 1 ', () => {
    expect(component).toBeTruthy();
  });
})

And below is the error message

Chrome 93.0.4577 (Linux 0.0.0) SomeComponent should create 1  FAILED
TypeError: Cannot read properties of undefined (reading 'get')
like image 438
Amir Avatar asked Sep 05 '25 03:09

Amir


1 Answers

In your test setup you provide the following activated route:

activatedRouteSpy = {
  snapshot: {
    paramMap: convertToParamMap({
      id: 'dads123',
      code: 'IBM',
    })
  }
};

And in your ngOnInit you access it like this:

this.id = this.route.snapshot.queryParamMap.get('id');

Your spy does not have a queryParamMap property, but only a paramMap. Rename it in your spy or supply both, the paramMap and a queryParamMap if you need both further down the line.

like image 92
pascalpuetz Avatar answered Sep 09 '25 15:09

pascalpuetz