首页 > 解决方案 > TypeError:无法读取未定义的属性(读取“和”)

问题描述

请帮忙!尝试运行浅集成测试时,我得到了上面的类型错误。

我已经多次查看我的代码以检查我是否有问题,但一切似乎都已到位。

我正在努力让这个测试通过。

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

它在 Karma 中一直因此错误而失败。

TypeError:无法读取未定义的属性(读取“和”)

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

标签: javascriptangularunit-testingtestingintegration-testing

解决方案


mockHeroService 方法中的引号未正确放置。

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

应该是这个。

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


推荐阅读