失败:预期一个条件匹配请求"Match URL method: GET"未找到任何条件



你好,我正在尝试在我的茉莉花单元测试中对api进行模拟GET调用,它返回我url未发现错误。

我在服役时这样做过。规格文件:

it('GET call for store details API', waitForAsync(inject([HttpTestingController, AuthService],
(httpClient: HttpTestingController, authService: AuthService) => {
var obj = {
"IsSuccess": true,
"Result": [
{
"Details": "Test"
}
]
}
authService.getStoreDetails()
.subscribe((get: any) => {
expect(get).toBe(obj);
});
const successRequest = httpTestingController.expectOne(environment.baseUrl1 + '/api/details/10/0');
expect(successRequest.request.method).toEqual('GET');
successRequest.flush(obj);
httpTestingController.verify();
})));

当我在没有多个端点ex; api/user的其他GET调用中做同样的事情时,测试工作正常。如何解决这个问题以及使用特定参数的GET ?

编辑:-

添加service.ts

createId() {
const ids = localStorage.getItem('ids');
return ids
}
// GET API for Store Details
getStoreDetails(): Observable<any> {
let headers = this.createAuthrorizationHeader();
let idd = this.createId();
var id = Number(JSON.parse(idd!));
return this.http
.get(`${environment.baseUrl1}/api/details/${id}/0`, { headers: 
headers })
.pipe(tap(res => {
console.log(res);
retry(2),
catchError(this.handleError)
})
)
}

也许你的URL是错误的expectOne或者它可能不是GET请求。

要调试,试试这个:

it('GET call for store details API', waitForAsync(inject([HttpTestingController, AuthService],
(httpClient: HttpTestingController, authService: AuthService) => {
var obj = {
"IsSuccess": true,
"Result": [
{
"Details": "Test"
}
]
}
// Edit - add this line
localStorage.setItem('ids', '10')
authService.getStoreDetails()
.subscribe((get: any) => {
// expect(get).toBe(obj);
expect(1).toBe(1);
});
// const successRequest = httpTestingController.expectOne(environment.baseUrl1 + '/api/details/10/0');
// expect(successRequest.request.method).toEqual('GET');
// successRequest.flush(obj);
// log out the URL you expect
console.log('url: ', environment.baseUrl1 + '/api/details/10/0');
httpTestingController.verify();
})));
afterEach(() => {
// clear local storage so it does not leak for other tests
localStorage.clear();
});

httpTestingController.verify()应该检测是否有任何正在进行的HTTP调用没有被处理(没有刷新)。

如果有,它将告诉您没有刷新的URL,您应该将此URL用于expectOne

如果没有,你有一个更大的问题,authService.getStoreDetails()不做API调用。

希望能帮助你调试。

编辑:我看到了这个问题,很可能ids在localStorage中未定义,您必须设置此项目。

最新更新