簡體   English   中英

如何測試可觀察的Angular 2?

[英]How to test observable Angular 2?

我有一個簡單的服務

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class TodoService {
    constructor(private http: Http) { }

    getTestData(): Observable<[{}]> {
        return this.http
            .get('https://jsonplaceholder.typicode.com/posts/1')
            .map(res => res.json())
    }
}

和一個簡單的組件

import { Component, OnInit} from '@angular/core';
import { TodoService } from './todo.service';

@Component({
    selector: 'todo-component',
    templateUrl: './todo-component.html',
    styleUrls: ['./todo.css']
})

export class TodoComponent implements OnInit {
    testList: Object; 

    constructor(private todoService: TodoService) { }

    ngOnInit() { 
        this.todoService
            .getTestData()
            .subscribe((testList)  => {
                this.testList = testList
            });

    }
}

而我正試圖測試這個

import { TestBed, async } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';

import { TodoComponent } from '../todo.component';
import { TodoService } from '../../todo/todo.service';

let todoService,
    fixture,
    comp,
    todoList = [],
    TodoServiceStub = { 
    getTestData: function() {
        return {
            userId: 1,
            id: 1,
            title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
            body: `quia et suscipit
                    suscipit recusandae consequuntur expedita et cum
                    reprehenderit molestiae ut ut quas totam
                    nostrum rerum est autem sunt rem eveniet architecto`
        }
    }
},
testDataFromService = { "someKey": "some Val"};

describe('Todo Component', () => {

    beforeEach(async(() => {

       TestBed.configureTestingModule({
           declarations: [ TodoComponent ],
            imports: [
                BrowserModule,
                FormsModule,
                HttpModule
            ],
            providers: [
                {
                    provide: TodoService, useValue: TodoServiceStub
                },
            ],
        })
        .compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(TodoComponent);
            comp = fixture.debugElement.componentInstance;

      todoService = fixture.debugElement.injector.get(TodoService);
            spyOn(todoService, 'getTestData').and.returnValue({ 
            subscribe: () => {} });
        });
    }));

    it('should get data from the http call', async(() => {
        comp.ngOnInit();

        expect(comp.testList).toBe(testDataFromService);
    }))
});

它得到:

Expected undefined to be Object({ someKey: 'some Val' }).

試圖遵循文檔,但comp.testList將不會被填充..如果我嘗試調試這似乎服務調用正在完成但在測試我無法達到解決價值..我在這里做錯了什么?

你缺少兩件事。

  1. 你沒有正確地模仿你的服務。 它應該返回一個Observable而不是原始數據。 使用Observable.of創建包含現有數據的observable。 它也應該返回一個數組而不是單個對象,因為這是您在實際服務中定義的。 如果您沒有使用某些rxjs運算符的常規導入文件,請務必導入運算符Observable.of
  2. 在init之后,您必須讓Observable返回數據,然后才能檢查它在組件中的存在。 使用fakeAsynctick

更新的代碼:

import { TestBed, async, tick, fakeAsync } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';

// if you have not already you should import the Observable.of operator for this test to work
import { Observable } from 'rxjs/Observable';

import { TodoComponent } from '../todo.component';
import { TodoService } from '../../todo/todo.service';

let todoService,
    fixture,
    comp,
    todoList = [],
    TodoServiceStub = { 
    getTestData: function() {
        // return an Observable like you do in your actual service and return an array
        return Observable.of([{
            userId: 1,
            id: 1,
            title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
            body: `quia et suscipit
                    suscipit recusandae consequuntur expedita et cum
                    reprehenderit molestiae ut ut quas totam
                    nostrum rerum est autem sunt rem eveniet architecto`
        }]);
    }
},
testDataFromService = { "someKey": "some Val"};

describe('Todo Component', () => {

    beforeEach(() => {

       TestBed.configureTestingModule({
           declarations: [ TodoComponent ],
            imports: [
                BrowserModule,
                FormsModule,
                HttpModule
            ],
            providers: [
                {
                    provide: TodoService, useValue: TodoServiceStub
                },
            ],
        })
        .compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(TodoComponent);
            comp = fixture.debugElement.componentInstance;
    }));

    it('should get data from the http call', fakeAsync(() => {
        comp.ngOnInit();

        tick();

        expect(comp.testList).toBe(testDataFromService);
    }))
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM