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、游戏颠覆性的策略玩法,...
透视智能!wepoker辅助方... 透视智能!wepoker辅助方法(透视)开挂辅助攻略(总是真的是有挂)-哔哩哔哩1、超多福利:超高返...
三分钟教程书!三加一辅助器,顺... 三分钟教程书!三加一辅助器,顺欣茶楼开挂,总结教程(有挂细节)-哔哩哔哩一、顺欣茶楼开挂软件透明挂的...
透视好友房!智星德州插件202... 透视好友房!智星德州插件2024最新版,pokemmo脚本辅助器下载,手筋教程(其实有挂)-哔哩哔哩...
透视app!htx矩阵wepo... 透视app!htx矩阵wepoker辅助(透视)开挂辅助挂(一贯是真的挂)-哔哩哔哩1、htx矩阵w...
4分钟大纲!决战十水三修改器,... 4分钟大纲!决战十水三修改器,牛总管辅助神器下载免费,科技教程(有挂解惑)-哔哩哔哩;1、上手简单,...
透视软件!wepoker怎么破... 透视软件!wepoker怎么破解游戏,wepoker透视app下载,指南教程(一贯真的是有挂)-哔哩...
透视系统!hhpoker软件安... 透视系统!hhpoker软件安装包(透视)开挂辅助器(一直存在有挂)-哔哩哔哩运hhpoker软件安...
第2分钟方式!心悦游戏万能透视... 第2分钟方式!心悦游戏万能透视辅助器免费,战神辅助发卡官网,解密教程(果真有挂)-哔哩哔哩1)心悦游...