Angular 8 用httpClient测试不发送请求
Angular 8 test with httpClient does not send requests
我正在尝试测试一项基本服务,但似乎 httpClient 没有将请求发送到我的本地 api 即使它说已通过测试
describe('MyService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports:[
//HttpClientTestingModule,
HttpClientModule,
TranslateModule.forRoot(),
RouterTestingModule.withRoutes([])
],
providers:
[
MyService
]
});
});
it('should return 1', inject([HttpClient,MyService],
(httpClient: HttpClient, myService: MyService) => {
const headers = {
'Content-Type': 'application/json',
'Authorization': "Bearer token"
}
httpClient.get("http://localhost:60200/path?parameter=1", { headers: headers }).subscribe((myModel:MyModel)=>{
expect(myModel.id).toBe(1);
}); //pass to the test but didn't sent to the api
myService.getById(parameter).subscribe((myModel: MyModel)=>{
expect(myModel.id).toBe(1);
}); //what I really want to test
}));
});
已解决,我只需要使用 TestBed.get 而不是注入来获取服务并使用来自 jasmine 的 'done' 进行异步请求。
...
myService = TestBed.get(MyService);
...
it('should return 1', (done) => {
myService.getById(parameter).subscribe((myModel: MyModel)=>{
expect(myModel.id).toBe(1);
done();
});
});
我正在尝试测试一项基本服务,但似乎 httpClient 没有将请求发送到我的本地 api 即使它说已通过测试
describe('MyService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports:[
//HttpClientTestingModule,
HttpClientModule,
TranslateModule.forRoot(),
RouterTestingModule.withRoutes([])
],
providers:
[
MyService
]
});
});
it('should return 1', inject([HttpClient,MyService],
(httpClient: HttpClient, myService: MyService) => {
const headers = {
'Content-Type': 'application/json',
'Authorization': "Bearer token"
}
httpClient.get("http://localhost:60200/path?parameter=1", { headers: headers }).subscribe((myModel:MyModel)=>{
expect(myModel.id).toBe(1);
}); //pass to the test but didn't sent to the api
myService.getById(parameter).subscribe((myModel: MyModel)=>{
expect(myModel.id).toBe(1);
}); //what I really want to test
}));
});
已解决,我只需要使用 TestBed.get 而不是注入来获取服务并使用来自 jasmine 的 'done' 进行异步请求。
...
myService = TestBed.get(MyService);
...
it('should return 1', (done) => {
myService.getById(parameter).subscribe((myModel: MyModel)=>{
expect(myModel.id).toBe(1);
done();
});
});