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
相关产品推荐
相关产品推荐

