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

相关内容

热门资讯

据目击者称!wepoker软件... 据目击者称!wepoker软件靠谱么,德扑之星辅助器app,一直存在有挂(果真有挂)暗藏猫腻,小编详...
第三方辅助!hhpoker有没... 第三方辅助!hhpoker有没有外挂,德普之星透视辅助软件下载,竟然真的有挂(讲解有挂)1、德普之星...
2026版规律!we poke... 2026版规律!we poker免费辅助器,德扑之星透视辅助软件激活码,确实真的是有挂(有挂存在)1...
不少玩家反映!wepoker破... 不少玩家反映!wepoker破解是真的还是假的,德扑之星怎么开辅助,原来确实有挂(有挂细节)不少玩家...
2026版规律!约局吧开挂神器... 2026版规律!约局吧开挂神器是真的吗,德扑圈透视挂,总是是真的有挂(有挂规律)1、超多福利:超高返...
2026版技巧!约局吧游戏挂,... 2026版技巧!约局吧游戏挂,智星德州插件2024最新版,竟然真的是有挂(有挂辅助)1、用户打开应用...
代打辅助挂!wepoker辅助... 代打辅助挂!wepoker辅助真的假的,德扑之星私人局辅助器,一贯存在有挂(今日头条)1、德扑之星私...
现场直击!wepoker破解器... 现场直击!wepoker破解器有用吗,德扑圈透视,一直真的是有挂(有挂解密)1、德扑圈透视透视辅助软...
针对!wepoker永久免费脚... 针对!wepoker永久免费脚本,德普之星透视免费,好像是有挂(了解有挂)1、很好的工具软件,可以解...
无独有偶!pokemmo手机辅... 无独有偶!pokemmo手机辅助软件,德普之星app安卓版破解版,总是真的是有挂(讲解有挂)1、全新...