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

相关内容

热门资讯

截至目前!pokemmo手机辅... 截至目前!pokemmo手机辅助软件,德普之星app安卓版破解版,本来真的是有挂(确实有挂)亲,关键...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker有插件吗,智星菠萝透视,确实真的有挂(有挂规律)1、起透看视 智星菠...
随着!wepoker好友局透视... 随着!wepoker好友局透视,德普之星透视辅助软件激活码,好像是真的有挂(有挂方式)1、德普之星透...
无独有偶!hh poker插件... 无独有偶!hh poker插件下载,德扑之星有辅助软件吗,确实真的有挂(有挂秘诀)1、点击下载安装,...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker辅助器官方,德普之星辅助器app,竟然存在有挂(详细教程)1、下载好...
第三方辅助挂!wepoker私... 第三方辅助挂!wepoker私人辅助器,德扑之星辅助工具如何设置,原来是真的有挂(有挂头条)1、每一...
代打辅助挂!hhpoker真的... 代打辅助挂!hhpoker真的假的,德扑之星透视,确实是有挂(有挂技术)1、让任何用户在无需德扑之星...
有消息称!hhpkoer辅助器... 有消息称!hhpkoer辅助器视频,德普之星透视软件免费入口官网,总是确实有挂(有挂教学)1、完成德...
不少玩家反映!wepoker怎... 不少玩家反映!wepoker怎么拿到好牌,德扑之星辅助工具如何设置,好像是真的有挂(存在有挂)1、下...
连日来!wepokerplus... 连日来!wepokerplus脚本,德普之星辅助软件,原来是真的有挂(有挂秘诀)1、德普之星辅助软件...