Angular 4.3中的单元测试HttpClientModule:HttpTestingController.expectOne(url)的未定义返回值 [英] Unit testing HttpClientModule in Angular 4.3: undefined return value from HttpTestingController.expectOne(url)
问题描述
我试图了解如何使用新HttpClientModule
中提供的模拟功能.我的测试代码几乎完全符合现有文档中显示的内容.但是,该doc示例并不完整-例如,至少缺少TestBad
和inject
的import语句.我认为@ angular/common/http中的HttpClient
也是如此.我的测试代码添加了这些.
I'm trying to understand how to use the mocking functionality provided as part of the new HttpClientModule
. My test code matches what's shown in the existing documentation almost exactly. However, the doc example is not complete - for example, at a minimum the import statement for TestBad
and inject
is missing. I assume the same is true of HttpClient
from @angular/common/http. My test code adds these.
此测试失败,因为req
在调用httpMock.expectOne
之后最终未定义.我很感激为什么会这样.
This test fails, as req
ends up being undefined after the httpMock.expectOne
call. I'd appreciate any insight into why that might be.
import { TestBed, inject } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('HttpClientTestingModule', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [ HttpClient, HttpTestingController]
}));
it('expects a GET request', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {
http
.get('/data')
.subscribe(data => expect(data['name']).toEqual('Test Data'));
const req = httpMock.expectOne('/data');
expect(req).toBeDefined();
expect(req.request.method).toEqual('GET');
req.flush({name: 'Test Data'});
httpMock.verify();
}));
});
推荐答案
尽管我不明白为什么会这样,但是通过从TestBed.configureTestingModule
中删除以下内容,我可以正常工作:
Though I don't understand why this is the case, I got it working, by removing the following from TestBed.configureTestingModule
:
providers: [HttpClient, HttpTestingController]
我欢迎您了解为什么我需要向providers
集合中添加我自己的服务,而不是HttpClient, HttpTestingController
.
I welcome any insight into why I need to add my own services to providers
collection, but not HttpClient, HttpTestingController
.
这篇关于Angular 4.3中的单元测试HttpClientModule:HttpTestingController.expectOne(url)的未定义返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!