要模拟Http ,您需要MockBackend
在. 然后您可以订阅它的连接并提供模拟响应Http
TestBed
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: Http, useFactory: (backend, options) => {
return new Http(backend, options);
},
deps: [MockBackend, BaseRequestOptions]
},
MockBackend,
BaseRequestOptions
]
});
});
我将如何测试 ngOnInit() 函数?
问题是Http.get
调用的异步性质。ngOnInit
调用时会被调用fixture.detectChanges()
,但是 Http 的异步特性导致测试在 Http 完成之前运行。为此我们使用,正如这里fakeAsync
提到的,但下一个问题是您不能使用and 。你可以用 a 破解它并在那里测试。那会奏效。我个人不喜欢它。fakeAsync
templateUrl
setTimeout
it('', async(() => {
setTimeout(() => {
// expectations here
}, 100);
})
就个人而言,我认为你一开始就有设计缺陷。Http
调用应该被抽象成一个服务,并且组件应该与服务交互,而不是直接与Http
. 如果您将设计更改为此(我会推荐),那么您可以像本示例中那样测试服务,并且对于组件测试,创建一个同步模拟,如本文所述。
这是我将如何做的完整示例
import { Component, OnInit, OnDestroy, DebugElement, Injectable } from '@angular/core';
import { CommonModule } from '@angular/common';
import { By } from '@angular/platform-browser';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { async, fakeAsync, inject, TestBed } from '@angular/core/testing';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
@Injectable()
class BooksService {
constructor(private http: Http) {}
getBooks(): Observable<string[]> {
return this.http.get('')
.map(res => res.json() as string[]);
}
}
class MockBooksService {
subscription: Subscription;
content;
error;
constructor() {
this.subscription = new Subscription();
spyOn(this.subscription, 'unsubscribe');
}
getBooks() {
return this;
}
subscribe(next, error) {
if (this.content && next && !error) {
next(this.content);
}
if (this.error) {
error(this.error);
}
return this.subscription;
}
}
@Component({
template: `
<h4 *ngFor="let book of books">{{ book }}</h4>
`
})
class TestComponent implements OnInit, OnDestroy {
books: string[];
subscription: Subscription;
constructor(private service: BooksService) {}
ngOnInit() {
this.subscription = this.service.getBooks().subscribe(books => {
this.books = books;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
describe('component: TestComponent', () => {
let mockService: MockBooksService;
beforeEach(() => {
mockService = new MockBooksService();
TestBed.configureTestingModule({
imports: [ CommonModule ],
declarations: [ TestComponent ],
providers: [
{ provide: BooksService, useValue: mockService }
]
});
});
it('should set the books', () => {
mockService.content = ['Book1', 'Book2'];
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
let debugEls: DebugElement[] = fixture.debugElement.queryAll(By.css('h4'));
expect(debugEls[0].nativeElement.innerHTML).toEqual('Book1');
expect(debugEls[1].nativeElement.innerHTML).toEqual('Book2');
});
it('should unsubscribe when destroyed', () => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
fixture.destroy();
expect(mockService.subscription.unsubscribe).toHaveBeenCalled();
});
});
describe('service: BooksService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: Http, useFactory: (backend, options) => {
return new Http(backend, options);
},
deps: [MockBackend, BaseRequestOptions]
},
MockBackend,
BaseRequestOptions,
BooksService
]
});
});
it('should return mocked content',
async(inject([MockBackend, BooksService],
(backend: MockBackend, service: BooksService) => {
backend.connections.subscribe((conn: MockConnection) => {
let ops = new ResponseOptions({body: '["Book1", "Book2"]'});
conn.mockRespond(new Response(ops));
});
service.getBooks().subscribe(books => {
expect(books[0]).toEqual('Book1');
expect(books[1]).toEqual('Book2');
});
})));
});