[英]How to return an Observable from a sample data [Angular]
我正在學習 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);
})
})
但我在控制台上收到此錯誤。 問題在於我的it()
方法and
內部:
src/app/heroes/heroes.second.spec.ts(32,39) 中的錯誤:錯誤 TS2339:屬性 'and' 不存在 > 在類型 '() => Observable' 上。
請指出我的錯誤。 隨意詢問更多代碼。 謝謝。
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();
}
}
問題在於 mocking,您需要將jasmine.createSpybj
的語法從
mockHeroService = jasmine.createSpyObj(['getHeroes', 'addHero', 'deleteHero']);
至
mockHeroService = jasmine.createSpyObj('HeroService', ['getHeroes', 'addHero', 'deleteHero']);
而且你還需要移動mockHeroService.getHeroes.and.returnValue(of(HEROES));
在創建組件之前。 因為在您創建組件時,您的構造函數和 ngOnInit 方法將被調用。 而且我們不會返回間諜數據,因為我們在之后編寫此語句。
您還需要更改創建間諜的語句:
let mockHeroService: jasmine.SpyObj<HeroService>;
它將解決您的問題。 請在此處查找文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.