Angular 在角度单元测试中,模拟HttpClient并返回可观察数据的正确方法是什么?
我已经为此工作了很长一段时间,令人尴尬。我正在尝试为angular应用程序编写一个单元测试,该应用程序模拟HttpClient,并为正在测试的代码返回一个可观察的值 我的测试是这样的Angular 在角度单元测试中,模拟HttpClient并返回可观察数据的正确方法是什么?,angular,rxjs,Angular,Rxjs,我已经为此工作了很长一段时间,令人尴尬。我正在尝试为angular应用程序编写一个单元测试,该应用程序模拟HttpClient,并为正在测试的代码返回一个可观察的值 我的测试是这样的 beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ ProjectComponent ], imports: [RouterTestingModule, HttpCl
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ProjectComponent ],
imports: [RouterTestingModule, HttpClientTestingModule],
providers: [
HttpClient
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ProjectComponent);
component = fixture.componentInstance;
fixture.detectChanges();
var service = TestBed.get(HttpClient);
var obs = Observable.create( observer => {
observer.next({'hi':'hi'});
observer.complete();
});
spyOn(service, 'get').and.returnValue(obs);
});
it('should create', () => {
expect(component).toBeTruthy();
});
我要测试的代码如下所示
ngOnInit(): void {
console.log('starting');
const x = this.http.get('http://localhost:8080/project')
x.subscribe((response: any) => {
console.log('$$$$$$');
console.log(response);
this.projects = response;
}, e => {
console.log(e);
});
}
正如您所看到的,我希望get方法将observable作为模拟响应返回。如果我在ngOninit方法中调试变量x,我会看到可观察的对象出现在那里。但从未调用subscribe函数。这是怎么回事?如何获取要调用的subscribe函数?我是否以错误的方式创造/嘲弄可观察事物。。。提前感谢。根据文档,您需要使用
HttpTestingController
而不是监视HttpClient
const httpMock:HttpTestingController=TestBed.get(
HttpTestingController,
);
//模拟请求。
const req=httpMock.expectOne('http://localhost:8080/project');
expect(request.method).toEqual('GET');
要求刷新([假、真、假]);
httpMock.verify();
请参阅,但请注意,组件通常不应直接使用HttpClient-使用服务来提取传输层的详细信息。本主题中有许多文章。你可以从这里开始: