[英]How to inject HttpClient in module mock
为了测试,我想用一个模拟来模拟我的依赖模块NavigationService
。 在模拟类中,我需要发出 HTTP 请求,因此我需要将HttpClient
注入到我的模拟类中。 这是我的beforeEach
:
beforeEach (() => {
TestBed.configureTestingModule ({
imports: [HttpClient, RouterTestingModule],
providers: [
{
provide: NavigationService, useClass: class {
constructor (httpClient: HttpClient) {
}
method1() {
return this.httpClient.get('/some-url');
}
},
},
]
});
});
但这不起作用,它在每次测试时都会出错:
Error: Can't resolve all parameters for class_1: (?).
那么如何正确地将HttpClient
注入到模拟类中呢?
您需要注入HttpTestingController
以使用HttpClient
的模拟。 这是我的操作方法(我的ProductService
在getProducts()
发出 HTTP 请求):
describe('ProductService', () => {
let productService: ProductService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ProductService]
});
productService = TestBed.get(ProductService);
httpMock = TestBed.get(HttpTestingController);
});
it('should successfully get products', async(() => {
const productData: Product[] = [{ "id":"0", "title": "First Product", "price": 24.99 }];
productService.getProducts()
.subscribe(res => expect(res).toEqual(productData));
// Emit the data to the subscriber
let productsRequest = httpMock.expectOne('/data/products.json');
productsRequest.flush(productData);
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.