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

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

请帮忙!我在尝试 运行 浅层集成测试时遇到上面的类型错误。

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

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

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

它在 Karma 中一直失败并出现此错误。

TypeError: 无法读取未定义的属性(读取 '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)
  });
});

我不确定您使用的是什么单元测试框架:

你的线路在这里

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

通过错误,我可以看出编译器正在尝试从对象 mockHeroService.getHeroes 中读取 属性 and。但是 mockHeroService.getHeroes 本身是未定义的。所以编译器无法读取 undefined

and

问题就在这里mockHeroService.getHeroes

请检查 mockHeroService 与 jasmine

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

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

应该是这个。

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