测量角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服务。 –