Angular的HttpTestingController无法匹配带参数的URL
创始人
2024-10-24 06:00:55
0次

当使用HttpTestingController模拟HTTP请求时,有时会出现无法匹配带参数的URL的问题。此时需要通过传递HttpParams对象来解决这一问题。

以下是一个使用HttpParams对象传递参数的代码示例:

import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';
import { HttpClient, HttpParams } from '@angular/common/http';

describe('MyService', () => {
  let service: MyService;
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [MyService]
    });

    service = TestBed.inject(MyService);
    httpTestingController = TestBed.inject(HttpTestingController);
    httpClient = TestBed.inject(HttpClient);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  it('should send request with query string parameter', () => {
    // Define the value we expect to be returned by the mock backend
    const expectedValue = 'value';

    // Set up the request params
    const params = new HttpParams().set('paramName', 'paramValue');

    // Use the HttpClient to send the request and subscribe to the response
    httpClient.get('https://my-api.com/api-endpoint', {params}).subscribe((response) => {
      expect(response).toEqual(expectedValue);
    });

    // Define the mock response and pass it to the expectOne method of the HttpTestingController
    const req = httpTestingController.expectOne('https://my-api.com/api-endpoint?paramName=paramValue');
    req.flush(expectedValue);
  });
});

在上述代码中,我们通过创建一个HttpParams对象并传递给HttpClient的get方法来设置请求的参数。然后,我们使用HttpTestingController的expectOne方法来定义模拟的响应并指定带参数的URL来匹配请求。最后,我们通过调用flush方法将预期的响应返回给请求。

这种做法可以帮助我们解决HttpTestingController无法匹配带参数的URL的问题。

相关内容

热门资讯

WPK工具!AApoker技巧... WPK工具!AApoker技巧辅助ai,哈糖大菠萝万能挂,本来是有ai辅助机巧1、每一步都需要思考,...
WPK工具!AApoker神器... WPK工具!AApoker神器辅助ai,德普之星怎么设置埋牌,总是存在有ai辅助模块1、金币登录送、...
WPK官网!菠萝智星德州教程辅... WPK官网!菠萝智星德州教程辅助器ai,佛手在线大菠萝为什么都输,竟然有ai辅助器策略1、佛手在线大...
WPK安装!德州扑克攻略辅助器... WPK安装!德州扑克攻略辅助器ai,拱趴大菠萝挂怎么安装,都是存在有ai辅助器总结所有人都在同一条线...
WPK真假!微扑克技巧辅助器a... WPK真假!微扑克技巧辅助器ai,菠萝德普辅助器免费版在哪里,果然有ai辅助器诀窍进入游戏-大厅左侧...
WPK私人局!WePoKer方... WPK私人局!WePoKer方法透视挂ai,德扑之星透视辅助,本来有ai透视挂窍要1、完成德扑之星透...
WPK安装!WPK技巧透视挂a... WPK安装!WPK技巧透视挂ai,约局吧游戏挂,竟然真的有ai透视挂窍要1、约局吧游戏挂有没有辅助教...
WPK辅助!aapoker技巧... WPK辅助!aapoker技巧透视挂ai,aapoker怎么拿好牌,总是存在有ai透视挂诀窍1、完成...
WPK靠谱!wpk软件辅助ai... WPK靠谱!wpk软件辅助ai,wpk有那种辅助吗,本来真的是有ai辅助攻略1、完成wpk有那种辅助...
WPK模拟器!红龙扑克脚本辅助... WPK模拟器!红龙扑克脚本辅助ai,wpk刷入池率脚本,总是真的是有ai辅助手段暗藏猫腻,小编详细说...