Home > database >  TypeError: Cannot read properties of undefined (reading 'and')
TypeError: Cannot read properties of undefined (reading 'and')

Time:11-11

Please help! I get the type error up above when trying to run a shallow integration test.

I have severally looked through my code to check if I have something amiss, but everything seems to be in place.

I'm trying to get this test to pass.

expect(fixture.componentInstance.heroes.length).toBe(3)

It keeps failing with this error in Karma.

TypeError: Cannot read properties of undefined (reading 'and')

import { ComponentFixture, TestBed } from "@angular/core/testing"
import { of } from "rxjs";
import { HeroService } from "../hero.service";
import { HeroesComponent } from "./heroes.component"

describe('HeroesComponent (shallow tests)', () => {
  let fixture: ComponentFixture<HeroesComponent>;
  let mockHeroService;
  let HEROES;  

  beforeEach(() =>{
    HEROES = [
      {id:1, name: 'SpiderDude', strength: 8},
      {id:2, name: 'Wonderful Woman', strength: 24},
      {id:3, name: 'SuperDude', strength: 55}
    ];
    mockHeroService = jasmine.createSpyObj(['getHeroes, addHero, deleteHero']);
    TestBed.configureTestingModule({
      declarations: [HeroesComponent],
      providers: [
        { provide: HeroService, useValue: mockHeroService}
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    fixture = TestBed.createComponent(HeroesComponent)
  })

  it('should set heroes correctly from the service', () => {
    mockHeroService.getHeroes.and.returnValue(of(HEROES))
    fixture.detectChanges();

    expect(fixture.componentInstance.heroes.length).toBe(3)
  });
});

CodePudding user response:

I'm not sure what Unit test framework you are using:

Your line here

 mockHeroService.getHeroes.and.returnValue(of(HEROES))

By the the error, I can tell that the compiler are trying to read property and from object mockHeroService.getHeroes. But the mockHeroService.getHeroes itself is undefined. So the compiler can not read and of undefined

The problem is here mockHeroService.getHeroes

Please check the mockHeroService with jasmine

CodePudding user response:

The quotes in the mockHeroService methods are not placed correctly.

mockHeroService = jasmine.createSpyObj(['getHeroes, addHero, deleteHero']);

It should be this instead.

mockHeroService = jasmine.createSpyObj(['getHeroes', 'addHero', 'deleteHero']);

  • Related