Jasmine测试中调用ASP.NET Core Web API认证接口后代码停滞无报错的问题求助
Jasmine测试中调用ASP.NET Core Web API认证接口后代码停滞无报错的问题求助
大家好,我现在碰到一个非常棘手的问题,想请教下有没有朋友遇到过类似情况或者有解决方案:
我们团队有一套Angular应用的专属测试流程,需要通过Jasmine完成身份认证后调用ASP.NET Core Web API。因为已经搭建了大量UI测试案例,不想在集成测试里重复开发,所以要求这些UI测试既能基于模拟数据运行,也能对接真实数据。
现在的核心问题是:connectClient方法永远走不到后续代码(就是代码里标了connectClient:never gets here的断点位置)。测试看起来像是“通过”了,但在发起http.post('.../connect/token')请求之后,connectClient里剩余的代码,以及Jasmine测试中的后续设置步骤(就是标了Jasmine setup:never gets here的调试器位置)完全不执行。
我试过各种排查手段:比如设置超大的超时时间jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000;、添加done()回调,但都没效果;而且全程没有任何超时错误提示。我还试过把connectClient的调用替换成10秒的setTimeout,这时候流程就能正常等待并继续执行后续代码,完全符合预期。
下面是相关的代码片段:
Jasmine 测试代码
uiTestAuthService = TestBed.inject(UiTestAuthService) as jasmine.SpyObj<UiTestAuthService>; mockData = await mockDataService.getDynamicReportData(uiTestAuthService); debugger; //<<-- !! Jasmine setup:never gets here !! spyOn(mockCommonService, 'getReportData').and.returnValue(mockData); ... beforeEach(async () => { //jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000; fixture = TestBed.createComponent(ComponentToBeTested); component = fixture.componentInstance; await fixture.whenStable(); }); ... it('should render correctly', fakeAsync(() => { component = fixture.componentInstance; expect(component).toBeTruthy(); }));
MockDataService 代码
export class MockDataService { async getDynamicReportData(uiTestAuthService: UiTestAuthService, myReportTypeId: any): Promise<any> { var http: HttpClient; var token; [token, http] = await uiTestAuthService.connectClient( 'https://identity-server.my-domain.com', 'client_credentials', 'my-client-id', 'my-client-secret' ); if (token) { var url = 'https://api.my-domain.com'; var reportTypeId = 9999; let apiUrl = `${url}/api/Report/${reportTypeId}` var json = JSON.parse('{"MyVariable1":"my-value-1","MyVariable2":"my-value-2",...}') const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`); return http.post(apiUrl, JSON.stringify(json), { headers }).pipe(map((resp: any) => { return Promise.resolve(resp.Result.Data); })); } } }
UiTestAuthService 的 connectClient 方法
export class UiTestAuthService { http: HttpClient; constructor( httpClient: HttpClient ) { this.http = httpClient; } async connectClient( authBaseAddress: string, grant_type: string, client_id: string, client_secret: string ): Promise<[string, HttpClient] | null> { const form = new HttpParams() .set('grant_type', grant_type) .set('client_id', client_id) .set('client_secret', client_secret); let retry = false; let retryCount = 0; let jsonContent: any = null; var _this = this; do { try { const response = await firstValueFrom( _this.http.post<any>(`${authBaseAddress}/connect/token`, form.toString(), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }) .pipe( catchError(error => { console.error('Error during token retrieval:', error); return throwError(() => new Error('Failed to get authentication token')); }) ) ) debugger; //<<-- !! connectClient:never gets here !! jsonContent = response; retry = false; } catch (error) { console.error(`An error occurred while acquiring a token\nTime: ${new Date()}\nError:`, error); retry = true; retryCount++; await new Promise(res => setTimeout(res, 30000)); // wait 30 seconds } } while (retry && retryCount < 3); if (!jsonContent) { console.warn('Cancelling attempt to contact the report service.'); return null; } const accessToken = jsonContent.access_token; return Promise.resolve([accessToken, _this.http]); } }
有没有朋友遇到过类似的问题?或者能给我一些排查的方向?
内容来源于stack exchange
相关产品推荐
相关产品推荐

