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的问题。

相关内容

热门资讯

第8分钟带你科普!欢聚水鱼智能... 第8分钟带你科普!欢聚水鱼智能辅助,奇迹陕西辅助,揭秘教程(有挂细节)-哔哩哔哩;无需打开直接搜索加...
第一分钟带你科普!博乐填大坑图... 第一分钟带你科普!博乐填大坑图片,福州十八扑外卦,曝光教程(有挂规律)-哔哩哔哩;无需打开直接搜索加...
四分钟带你讲解!潮汕来物局开挂... 潮汕来物局开挂方法 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: ...
第三分钟带你透视!潮汕透视辅助... 第三分钟带你透视!潮汕透视辅助,决战卡五星开挂方法,必赢教程(有挂规律)-哔哩哔哩 【无需打开直接搜...
第8分钟带你开挂!天胡辅助脚本... 天蝎大厅辅助开挂教程视频分享装挂详细步骤在当今的网络游戏中,天蝎大厅辅助作为一种经典的娱乐方式,吸引...
第8分钟带你辅助!微信茶馆辅助... 第8分钟带你辅助!微信茶馆辅助器,全来潜山跑风破解版安卓,AI教程(揭秘有挂)-哔哩哔哩全来潜山跑风...
第五分钟带你发现!微信微乐游戏... 【亲,微信微乐游戏辅助脚本 这款游戏可以开挂的,确实是有挂的,很多玩家在这款微信微乐游戏辅助脚本中打...
5分钟带你辅助!wepoker... 5分钟带你辅助!wepoker插件程序,兴动互娱辅助器视频,大神讲解(新版有挂)-哔哩哔哩【无需打开...
第九分钟带你透视!新上游辅助,... 第九分钟带你透视!新上游辅助,悠闲卡五星辅助,攻略教程!(存在有挂)-哔哩哔哩1、下载安装好悠闲卡五...
十分钟带你透视!湖湘互娱牛牛,... 十分钟带你透视!湖湘互娱牛牛,胡乐辅助脚本,实用技巧(证实有挂)-哔哩哔哩>>您好:软件加薇1367...