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

相关内容

热门资讯

必知教程!阿拉斗牌辅助,xpo... 必知教程!阿拉斗牌辅助,xpoker透视辅助,辅助教程(确实有挂);小薇(透视辅助)致您一封信;亲爱...
记者揭秘!边锋干瞪眼辅助,we... 记者揭秘!边锋干瞪眼辅助,wepoker辅助器有哪些功能,细节揭秘(果真有挂);详细边锋干瞪眼辅助攻...
推荐十款!微信小程序功夫川麻小... 您好:微信小程序功夫川麻小程序辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现...
发现玩家!全民牛牛拼三张开挂,... 发现玩家!全民牛牛拼三张开挂,wepoker底牌透视,安装教程(存在有挂);最新版2026是一款经典...
发现玩家!老k游戏辅助,hhp... 发现玩家!老k游戏辅助,hhpoker外挂靠谱吗,新2025版(有挂透视)是一款可以让一直输的玩家,...
分享一款!新超凡大厅辅助,hh... 分享一款!新超凡大厅辅助,hhpoker可以控制吗,切实教程(有挂辅助);1、在新超凡大厅辅助ai机...
程序员教你!微信辅助工具,哈糖... 程序员教你!微信辅助工具,哈糖大菠萝攻略,细节方法(真的有挂);1、这是跨平台的微信辅助工具黑科技,...
一分钟了解!广东雀神挂件脚本开... 一分钟了解!广东雀神挂件脚本开挂,pokemmo辅助脚本,wpk教程(有挂分享);【福星临门,好运相...
大神推荐!广西老友玩游戏辅助器... 大神推荐!广西老友玩游戏辅助器,微扑克辅助,新2025版(有挂透视);一、广西老友玩游戏辅助器AI软...
必备教程!科乐天天踢辅助视频,... 必备教程!科乐天天踢辅助视频,来玩app破解,详细教程(的确有挂);科乐天天踢辅助视频软件透明挂作为...