下面是AbcService。ts文件,我想测试这个服务文件是否返回指定的请求/数据它按预期调用了1次,但拒绝了承诺,没有返回任何东西我得到的错误是HttpClient。波斯特接到了一个电话,里面有很多争论配置的策略指定其他参数。
请帮忙?如何在茉莉花中为上述代码编写测试用例?
@injectable({
provideIn:'root'
})
export class AbcService{
constructor(private client:HttpClient){}
async imbook(json: string): Promise<any>{
let search!: SearchDefinition;
search = Object.assign(JSON.parse(json));
const httpOptions={
headers: new HttpHeaders({
'content-Type':'application/json',
'Access-Control-Allow-Origin':'*'
})
};
const req =
this.client.post("https://abc.zone/api/data",search,httpOptions).pipe(timeout(360000))
.toPromise()
await req;
return req;
}
}
这是测试设置在规范文件
describe('AbcService',()=>{
let service: AbcService;
let httpclientspy: jasmine.spyObj<HttpClient>;
let httpclientspyobj: jasmine.createSpyObj('HttpClient',['post']);
});
beforeEach(()=>TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers:[AbcService,{
provide: HttpClient, useValue: httpclientspyobj
}]
}));
beforeEach(() =>{
service = TestBed.inject(AbcService);
client = TestBed.inject(HttpClient);
httpclientspy = TestBed.inject(HttpClient) as jasmine.SpyObj<HttpClient>
});
这里是测试用例。
it('it should call http post method and return req',()=>{
const json= '{"id":"1","count":"5","name":"book name"}';
const httpOptions={
headers: new HttpHeaders({
'Content-Type':'application/json',
'Access-Control-Allow-Origin':'*'})
};
httpclient.post.withArgs('https://abc.zone/api/data',json,httpOptions).and.resolveTo();
service.imbook(json);
expect(httpclientspy.post).toHavebeenCalledTimes(1);
})
按预期调用1次,但拒绝承诺,不返回任何内容我得到的错误是HttpClient。波斯特接到了一个电话,里面有很多争论配置的策略指定其他参数。
请帮忙?如何在茉莉花中为上述代码编写测试用例?
你可以试试:
describe('AbcService',()=>{
let service: AbcService;
let httpTestingController: HttpTestingController;
beforeEach(()=>TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers:[AbcService]
}));
beforeEach(() =>{
service = TestBed.inject(AbcService);
client = TestBed.inject(HttpTestingController);
});
// !! add async here
it('it should call http post method and return req', async ()=>{
const json= '{"id":"1","count":"5","name":"book name"}';
const httpOptions={
headers: new HttpHeaders({
'Content-Type':'application/json',
'Access-Control-Allow-Origin':'*'})
};
// !! get a handle on the promise
const promise = service.imbook(json);
// !! get a handle on the http request in flight
const req = client.expectOne(request => request.method === 'POST');
// !! send this response to the http call
req.flush({});
// !! await the promise
const result = await promise;
// !! expect the result to be what we sent
expect(result).toEqual({});
});
要了解有关使用Http调用测试服务的更多信息,请参阅此链接:https://testing-angular.com/testing-services/#testing-a-service-that-sends-http-requests.