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刷入池率脚本,... 分享透视!wpk刷入池率脚本,微信小程序微乐怎么才能发好牌,讲义教程(有挂存在)-哔哩哔哩1、玩家可...
揭幕透视!智星德州可以透视吗,... 揭幕透视!智星德州可以透视吗,微信微乐跑得快游戏辅助脚本,绝活儿教程(有挂教学)-哔哩哔哩1、在智星...
教你透视!hhpoker有后台... 教你透视!hhpoker有后台操控吗,小程序微乐辅助器下载,操作教程(有挂秘诀)-哔哩哔哩1、点击下...
总结透视!pokemmo辅助工... 总结透视!pokemmo辅助工具,小程序微乐辅助器2.0,策略教程(确实有挂)-哔哩哔哩;1、每一步...
关于透视!newpoker脚本... 关于透视!newpoker脚本,微信小程序微乐辅助器ios,手筋教程(存在有挂)-哔哩哔哩1)new...
推荐透视!aapoker插件下... 推荐透视!aapoker插件下载,微乐广西麻辣,方针教程(有挂工具)-哔哩哔哩亲,关键说明,aapo...
开挂透视!poker红龙辅助,... 开挂透视!poker红龙辅助,微信小程序微乐安徽辅助器,要领教程(有挂猫腻)-哔哩哔哩1、每一步都需...
普及透视!wpk模拟器,微乐麻... 普及透视!wpk模拟器,微乐麻将自建房app,窍要教程(果真有挂)-哔哩哔哩1、不需要AI权限,帮助...
详情透视!wejoker辅助器... 详情透视!wejoker辅助器要钱玩吗,微乐自建房脚本如何下载,策略教程(有挂细节)-哔哩哔哩1、进...
普及透视!佛手在线大菠萝辅助,... 普及透视!佛手在线大菠萝辅助,微乐小程序插件免费,步骤教程(有人有挂)-哔哩哔哩1、打开软件启动之后...