我正在尝试了解如何使用作为新HttpClientModule
的一部分提供的模拟功能。我的测试代码几乎完全匹配现有文档中显示的内容。但是,doc示例并不完整 - 例如,至少缺少TestBad
和inject
的导入语句。我假设来自@ angular / common / http的HttpClient
也是如此。我的测试代码添加了这些。
此测试失败,因为在req
调用后httpMock.expectOne
最终未定义。我很欣赏为什么会这样。
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();
}));
});
答案 0 :(得分:7)
虽然我不明白为什么会这样,但是通过从TestBed.configureTestingModule
删除以下内容,我得到了它的工作:
providers: [HttpClient, HttpTestingController]
我欢迎任何洞察我为什么需要将自己的服务添加到providers
集合,而不是HttpClient, HttpTestingController
。