【发布时间】:2021-12-20 09:11:39
【问题描述】:
请帮忙!尝试运行浅层集成测试时出现上述类型错误。
我已经多次查看我的代码以检查我是否有问题,但一切似乎都已到位。
我正在努力让这个测试通过。
expect(fixture.componentInstance.heroes.length).toBe(3)
它在 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)
});
});
【问题讨论】:
-
你没有正确地模拟你的英雄服务。
-
你是对的。
标签: javascript angular unit-testing testing integration-testing