Search code examples
javascriptangularunit-testingtestingintegration-testing

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


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

Solution

  • 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']);