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

相关内容

热门资讯

开挂辅助安装"哈糖大... 哈糖大菠萝能开挂吗是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我...
总算明白“wepoker发牌规... 无需打开直接搜索加微信客服(136704302)咨询了解wepoker发牌规律总结辅助器目前(微信:...
开挂辅助安装"pok... 开挂辅助安装"pokemmo修改器手机版"开挂(透视)辅助平台(有挂神器)1、下载安装好pokemm...
三分钟了解“wepoker有什... 无需打开直接搜索;操作使用教程:三分钟了解“wepoker有什么技巧”开挂辅助插件(透视)透明教程1...
开挂辅助脚本"哈糖大... 您好:这款哈糖大菠萝怎么开挂游戏是可以开挂的,确实是有挂的,很多玩家在这款哈糖大菠萝怎么开挂游戏中打...
一起来讨论“wepoker透视... 您好:wepoker透视挂使用教程这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现...
开挂辅助插件"拱趴大... 开挂辅助插件"拱趴大菠萝有什么挂"开挂(透视)辅助软件(有挂秘诀) 【无需打开直接搜索加薇13670...
终于清楚“wpk挂在哪里买到真... 无需打开直接搜索加微信客服(136704302)咨询了解wpk挂在哪里买到真的辅助器目前(微信:13...
专业讨论“wepoker发牌的... >>您好:wepoker发牌的规律与打法技巧分享软件加扣扣群确实是有挂的,很多玩家在这款游戏中打牌都...
开挂辅助平台"aap... 开挂辅助平台"aapoker透视脚本入口"开挂(透视)辅助神器(存在有挂) 了解更多开挂安装加(13...