You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular浅集成测试报Cannot read properties of undefined (reading 'and')如何解决

问题根因

  • 创建jasmine模拟服务对象时方法名参数写错:jasmine.createSpyObj(['getHeroes, addHero, deleteHero']) 这里把三个方法名放在了同一个字符串里,导致mock对象上不存在getHeroes属性,只有一个键为"getHeroes, addHero, deleteHero"的间谍方法,调用mockHeroService.getHeroes会返回undefined,读取and属性就会抛出对应错误。
  • 代码中使用了NO_ERRORS_SCHEMA但未引入,运行时也会触发相关报错。

修复后完整代码

import { ComponentFixture, TestBed } from "@angular/core/testing"
import { NO_ERRORS_SCHEMA } from "@angular/core"
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)
  });
});

内容的提问来源于stack exchange,提问作者Abayomi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:15:08