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

相关内容

热门资讯

一分钟了解!hhpoker为什... 一分钟了解!hhpoker为什么一直输,hhpoker脚本,竟然有挂(真的有挂)1、任何透视是真的假...
据通报!wepoker私人定制... 据通报!wepoker私人定制透视,德普之星有透视辅助吗,果然存在有挂(有挂辅助)该软件可以轻松地帮...
最新研发!wepoker养号规... 最新研发!wepoker养号规律,德普之星透视辅助,好像是有挂(有挂秘诀)亲,关键说明,透视脚本安卓...
最终!wepoker好友助力码... 最终!wepoker好友助力码,智星德州有脚本吗,本来存在有挂(有挂详细)1、首先打开智星德州有脚本...
出现新变化!德扑之心免费透视,... 出现新变化!德扑之心免费透视,德普之星怎么设置埋牌,其实是有挂(果真有挂)1、德普之星怎么设置埋牌有...
一分钟带你了解!约局吧如何查看... 一分钟带你了解!约局吧如何查看是否有挂,wepoker透视有吗,切实是真的有挂(有挂讲解)1、公共底...
此事引发网友热议!WePOke... 此事引发网友热议!WePOker有没有透视方法,德普之星辅助器,原来真的是有挂(有挂秘诀)1、任何德...
记者揭秘!pokemmo免费脚... 记者揭秘!pokemmo免费脚本,hhpoker辅助软件下载,都是存在有挂(有挂技术)1、玩家可以在...
总结辅助挂!wepoker辅助... 总结辅助挂!wepoker辅助器安装包定制,德普之星有透视辅助吗,一贯存在有挂(有挂头条);1、德普...
今日头条!wepokerplu... 今日头条!wepokerplus透视脚本免费,wepoker有没有挂,真是真的是有挂(有挂方法)1、...