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

相关内容

热门资讯

此事引发广泛关注!智星德州有脚... 此事引发广泛关注!智星德州有脚本吗,德普之星透视辅助软件下载,果然是有挂(有挂解惑)德普之星透视辅助...
攻略讲解!卡农血拼辅助,蜀山四... 攻略讲解!卡农血拼辅助,蜀山四川小程序破解版下载,详细脚本(有挂头条)1、蜀山四川小程序破解版下载公...
据统计!pokemmo脚本辅助... 据统计!pokemmo脚本辅助,德普之星透视辅助软件下载,本来确实有挂(真实有挂)1、该软件可以轻松...
每日必备!天酷互娱有辅助工具嘛... 每日必备!天酷互娱有辅助工具嘛,网易游戏辅助工具,详细方法(详细教程)1、天酷互娱有辅助工具嘛免费脚...
据通报!wepoker数据分析... 据通报!wepoker数据分析工具,德扑之心免费透视,确实真的是有挂(有挂技巧)1、德扑之心免费透视...
一分钟揭秘!微乐a3纸牌有脚本... 一分钟揭秘!微乐a3纸牌有脚本,开心庄园辅助器免费,详细工具(有挂助手)1、让任何用户在无需开心庄园...
现有关情况通报如下!we po... 现有关情况通报如下!we poker辅助器v3.3,智星菠萝有挂吗,总是存在有挂(有挂功能)1)智星...
如何分辨真伪!微乐辅助脚本,来... 如何分辨真伪!微乐辅助脚本,来来舟山麻将辅助,详细器(了解有挂)1、金币登录送、破产送、升级送、活动...
迎来新发展!wepoker怎么... 迎来新发展!wepoker怎么破解游戏,如何下载德普之星辅助软件,确实是有挂(有挂技巧)1、如何下载...
一分钟揭秘!鸿狐大厅脚本,填大... 一分钟揭秘!鸿狐大厅脚本,填大坑微信小程序辅助,详细教程(真实有挂)1、不需要AI权限,帮助你快速的...