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手机辅助软件,微乐自建房道具有用吗,窍门教程(有挂头条)-哔哩哔哩pokem...
总结透视!wepoker怎么开... 总结透视!wepoker怎么开辅助,微乐脚本,要领教程(有挂猫腻)-哔哩哔哩1、这是跨平台的wepo...
总结透视!wepoker透视底... 总结透视!wepoker透视底牌,微乐脚本辅助器,教程书教程(有挂存在)-哔哩哔哩1、起透看视 we...
辅助透视!wepoker透视方... 辅助透视!wepoker透视方法,微乐家乡游戏攻略,指南教程(果真有挂)-哔哩哔哩所有人都在同一条线...
了解透视!hhpoker底牌透... 了解透视!hhpoker底牌透视脚本,微乐家乡app下载,要领教程(有挂方法)-哔哩哔哩1、玩家可以...
专业透视!扑克之星辅助,微乐麻... 专业透视!扑克之星辅助,微乐麻辣自建房辅助视频,妙计教程(的确有挂)-哔哩哔哩1、实时扑克之星辅助透...
了解透视!hhpoker怎么开... 了解透视!hhpoker怎么开透视,微乐游戏辅助脚本安卓,方式教程(有挂讲解)-哔哩哔哩1、hhpo...
科普透视!wpk辅助哪里买,微... 科普透视!wpk辅助哪里买,微乐家乡官方app,技法教程(有挂教程)-哔哩哔哩1.wpk辅助哪里买 ...
分享透视!德州局透视,微信微乐... 分享透视!德州局透视,微信微乐游戏有辅助吗,练习教程(确实有挂)-哔哩哔哩1、下载好德州局透视正确养...
揭露透视!we-poker软件... 揭露透视!we-poker软件,陕西微乐小程序脚本,妙计教程(发现有挂)-哔哩哔哩we-poker软...