为了测试,我想用mock模拟我的依赖模块NavigationService
。在mock类中,我需要发出HTTP请求,所以我需要将HttpClient
注入到我的mock类中。这是我的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
注入模拟类?
答案 0 :(得分:-1)
您需要注入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);
}));