我正在尝试在简单的Angular应用程序中测试异步函数。
使用此组件:
组件
import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
public posts:Post[];
constructor(public data:DataService) { }
ngOnInit() {
this.data.getPosts().subscribe((res) => this.posts = res);
}
}
export class Post{
public userId:number;
public id:number;
public title:string;
public body:string;
}
我可以通过数据服务层检索一个json帖子列表来填充帖子 PostComponent 类的属性。
服务
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class DataService {
constructor(public http: Http) { }
getPosts() {
return this.http.get('https://jsonplaceholder.typicode.com/posts').map(res => res.json());
}
}
所以我在suggestion之后写了这个Jasmine测试:
import { async, ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { DataService } from '../../services/data.service';
import { PostComponent } from './post.component';
import {Post} from '../post/post.component';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
describe('PostComponent', () => {
let component: PostComponent;
let fixture: ComponentFixture<PostComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpModule
],
declarations: [PostComponent],
providers: [DataService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PostComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('sholud call ngOnInit and fill Posts[]', async(() => {
const foo:Post[] = [];
const spy = spyOn(component, 'ngOnInit').and.returnValue(Observable.of(component.posts));
component.ngOnInit();
fixture.detectChanges();
expect(component.posts.length).toBeGreaterThan(1);
}));
});
但是我收到了这个错误:
失败:无法读取属性&#39;长度&#39;未定义的
TypeError:不能 读取属性&#39;长度&#39;未定义的
我该如何测试?
答案 0 :(得分:2)
使用此解决:
it('should call ngOnInit and fill Posts[]', () => {
spyOn(component, "ngOnInit").and.callThrough();
component.ngOnInit();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.posts.length).toBeGreaterThan(0);
});
});