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透视插件,智星德州辅助译码插件靠谱吗,都是真的是有挂(详细教程)该软件可以...
第三方辅助!we-poker辅... 第三方辅助!we-poker辅助,德普之星透视软件免费入口官网,都是存在有挂(有挂猫腻)1、进入到德...
现有说明如下!聚星ai辅助工具... 现有说明如下!聚星ai辅助工具收费多少,德普之星透视辅助软件是真的吗,总是真的有挂(有挂解惑)1、玩...
黑科技插件!约局吧app有挂吗... 黑科技插件!约局吧app有挂吗,德普之星辅助工具如何打开,其实存在有挂(有挂技巧)德普之星辅助工具如...
方法辅助挂!hhpoker一直... 方法辅助挂!hhpoker一直输有挂吗,智星菠萝可以辅助吗,原来真的有挂(新版有挂)1、完成智星菠萝...
经核实!poker红龙辅助,德... 经核实!poker红龙辅助,德扑之星透视辅助软件激活码,真是真的有挂(证实有挂)1、点击下载安装,德...
2026版方法!黑侠破解wep... 2026版方法!黑侠破解wepoker,德普之星辅助器怎么用,真是真的是有挂(发现有挂)1、德普之星...
技巧辅助挂!德普之星透视辅助软... 技巧辅助挂!德普之星透视辅助软件是真的吗,德扑之星透视免费,本来存在有挂(有挂讲解)1、德普之星透视...
日前!hhpoker是正规的吗... 日前!hhpoker是正规的吗,智星德州插件,一直真的是有挂(有挂功能)所有人都在同一条线上,像星星...
2026版总结!xpoker辅... 2026版总结!xpoker辅助器,智星德州插件,本来真的有挂(有挂头条)1、起透看视 智星德州插件...