我正在学习Angular中的浅层集成测试。我有一个组件HeroesComponent
。它具有一个服务注入,即HeroService
和一个子组件HeroComponent
。目前,我仅尝试模拟服务注入。我在HEROES: Hero[]
中有一些示例数据,这是我的规格文件:
heores.component.spec.ts
import { Hero } from "../hero"
import { HeroesComponent } from "./heroes.component";
import { HeroService } from "../hero.service";
import { TestBed, ComponentFixture } from "@angular/core/testing";
import { NO_ERRORS_SCHEMA } from "@angular/core";
import { of } from "rxjs/internal/observable/of";
describe('HeroesComponent', () => {
let HEROES: Hero[];
let mockHeroService: HeroService;
let fixture: ComponentFixture<HeroesComponent>
beforeEach(() => {
HEROES = [
{id: 1, name: 'Ant man', strength: 20},
{id: 2, name: 'Gohan', strength: 10},
{id: 3, name: 'Goku', strength: 5}
];
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', () => {
// arrange
mockHeroService.getHeroes.and.returnValue(of(HEROES));
// act
fixture.detectChanges();
// assert
expect(fixture.componentInstance.heroes.length).toBe(3);
})
})
})
但是我在控制台上收到此错误。问题出在我的and
方法中的it()
:
src / app / heroes / heroes.second.spec.ts(32,39)中的错误:错误TS2339:属性'and'不存在>类型'()=>可观察'。
请指出我的错误。随时要求更多代码。谢谢。
PS:这是HeroesComponent
的代码:
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes: Hero[];
constructor(private heroService: HeroService) { }
ngOnInit() {
this.getHeroes();
}
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
add(name: string): void {
name = name.trim();
var strength = 11
if (!name) { return; }
this.heroService.addHero({ name, strength } as Hero)
.subscribe(hero => {
this.heroes.push(hero);
});
}
delete(hero: Hero): void {
this.heroes = this.heroes.filter(h => h !== hero);
this.heroService.deleteHero(hero).subscribe();
}
}
问题在于模拟,您需要从[]更改jasmine.createSpybj
的语法>
mockHeroService = jasmine.createSpyObj(['getHeroes', 'addHero', 'deleteHero']);
to
mockHeroService = jasmine.createSpyObj('HeroService', ['getHeroes', 'addHero', 'deleteHero']);
它将解决您的问题。请找到documentation here