我有一个简单的服务
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将不会被填充。如果我尝试调试这一点,似乎服务调用已经完成,但在测试中,我无法达到解析值的目的。我在这里做错什么了?
发布于 2017-06-18 09:29:42
你错过了两件事。
Observable而不是原始数据。使用Observable.of创建可观察到的现有数据。它还应该返回一个数组,而不是一个对象,因为这是您在实际服务中定义的。如果您没有使用过的rxjs操作符的某种通用导入文件,请确保导入操作符Observable.of。Observable返回数据,然后才能检查它是否存在于组件中。为此使用fakeAsync和tick。更新代码:
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);
}))
});https://stackoverflow.com/questions/44613026
复制相似问题