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

相关内容

热门资讯

今日头条透视挂技巧!廊坊麻将多... 今日头条透视挂技巧!廊坊麻将多功能透视挂技巧,廊坊麻将其实真的是有透视挂技巧1、廊坊麻将透视辅助软件...
推荐一款辅助技巧!廊坊麻将多功... 推荐一款辅助技巧!廊坊麻将多功能辅助技巧,廊坊麻将好像真的是有辅助技巧1、完成廊坊麻将有辅助插件,帮...
一起来探讨透视器软件!千游科技... 一起来探讨透视器软件!千游科技多功能透视器软件,千游科技其实有透视器软件1、千游科技免费脚本咨询教程...
每日必看推荐辅助方法!喜乐多功... 每日必看推荐辅助方法!喜乐多功能辅助方法,喜乐切实真的有辅助方法1、不需要AI权限,帮助你快速的进行...
传递经验外挂软件!小闲巴渝棋牌... 传递经验外挂软件!小闲巴渝棋牌多功能外挂软件,小闲巴渝棋牌确实是真的有外挂软件1、每一步都需要思考,...
科技通报透视器脚本!大宝江苏麻... 科技通报透视器脚本!大宝江苏麻将多功能透视器脚本,大宝江苏麻将一直是有透视器脚本1.大宝江苏麻将 选...
我来教教大家外挂app!白金岛... 我来教教大家外挂app!白金岛红拐弯多功能外挂app,白金岛红拐弯切实存在有外挂app1、玩家可以在...
最新技巧开挂攻略!丫丫棋牌多功... 最新技巧开挂攻略!丫丫棋牌多功能开挂攻略,丫丫棋牌果然真的有开挂攻略;1、首先打开丫丫棋牌辅助器下载...
一分钟快速了解辅助器攻略!奉化... 一分钟快速了解辅助器攻略!奉化冲刺多功能辅助器攻略,奉化冲刺确实有辅助器攻略1、不需要AI权限,帮助...
揭秘攻略辅助app!白金岛红拐... 揭秘攻略辅助app!白金岛红拐弯多功能辅助app,白金岛红拐弯其实真的有辅助app1、白金岛红拐弯辅...