測量角4了HTTPClient測試了HTTPClient角4 「預計undefined來定義」
在此之後post
在服務
getBlogs(){
return this._http.get(this.blogsURL+'blogs')
.map((result: Response) => {
this.blogs = result['blogs'];
return this.blogs;
})
}
然後測試: 我開始注入服務和HttpTestingController進入它的阻塞,但把它放在每個工作前也是如此。
問題時request.flush被稱爲發生等觸發的訂閱方法,他們還沒有結果返回
import { TestBed, inject } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import { BlogsService } from './blogs.service';
import { Blog } from '../models/blog';
describe('BlogsService',() => {
let service:BlogsService;
let blogsURL:string;
let httpMock:HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [BlogsService],
imports: [HttpClientTestingModule]
});
service = TestBed.get(BlogsService);
httpMock = TestBed.get(HttpTestingController);
blogsURL = 'http://localhost:3000/'
});
it('#getBlogs should return data',() => {
service
.getBlogs()
.subscribe(result => {
expect(result).toBeDefined();
expect(result.length).toBe(2);
expect(result).toEqual([
{
id: 1,
name: 'Foo',
numSales: 100
}, {
id: 2,
name: 'Bar',
numSales: 200
}
]);
});
// look up our request and access it
const request = httpMock.expectOne(blogsURL+'blogs');
// verify it is a GET
expect(request.request.method).toEqual('GET');
// Now, provide the answer to the caller above,
// flushing the data down the pipe to the caller and
// triggering the test's subscribe method
request.flush([
{
id: 1,
name: 'Foo',
numSales: 100
}, {
id: 2,
name: 'Bar',
numSales: 200
}
]);
//
// // make sure it actually got processed...
httpMock.verify();
});
});
感謝您的答覆,但我使用了HTTPClient角4,當我看到你的'this._http'我還以爲你使用不需要做 – Roy
嘛Http服務。 –