Угловой жасминовый тестовый заполнитель с подпиской - PullRequest
0 голосов
/ 02 мая 2018

Я пытаюсь проверить асинхронную функцию в простом угловом приложении.

Использование этого компонента:

Компонент

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());
  }
}

Итак, я написал этот тест Жасмин, следуя этому предложению :

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);
  }));
});

но я получаю эту ошибку:

Ошибка: не удалось прочитать свойство 'длина' из неопределенного

TypeError: невозможно читать свойство 'длина' из неопределенного

Как я могу это проверить?

1 Ответ

0 голосов
/ 03 мая 2018

Решено с помощью этого:

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);
    });
 });
...