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

相关内容

热门资讯

一分钟揭秘!拱趴大菠萝9人场技... 一分钟揭秘!拱趴大菠萝9人场技巧,微信新九五辅助,详细插件(有挂教程)运拱趴大菠萝9人场技巧辅助工具...
推荐一款!微乐自建房怎么提高胜... 推荐一款!微乐自建房怎么提高胜率,财神辅助模拟器,详细脚本(有挂解惑)1、超多福利:超高返利,海量正...
信息共享!聚财平台辅助,广西老... 信息共享!聚财平台辅助,广西老友玩有破解码,详细方法(有挂方法)一、广西老友玩有破解码可以开透视的定...
科技通报!潮娱乐鱼虾蟹公式辅助... 科技通报!潮娱乐鱼虾蟹公式辅助软件,多乐找刺激技巧辅助,详细挂(发现有挂)1、每一步都需要思考,不同...
最新技巧!微乐贵阳麻将辅助,德... 最新技巧!微乐贵阳麻将辅助,德扑之星安卓插件,详细教程(存在有挂)微乐贵阳麻将辅助辅助器是一种具有地...
我来教教大家!潮友会透视辅助教... 我来教教大家!潮友会透视辅助教程,道游互娱辅助,详细方法(有挂教程)1、完成潮友会透视辅助教程有辅助...
推荐十款!微信小程序挂件辅助,... 推荐十款!微信小程序挂件辅助,边锋老友辅助器,详细器(有挂规律)1、让任何用户在无需微信小程序挂件辅...
一分钟揭秘!圣游辅助器,吉祥填... 一分钟揭秘!圣游辅助器,吉祥填大坑机制原理,详细神器(有挂透明挂)1、超多福利:超高返利,海量正版游...
总算了解!宁夏欢乐划水辅助,微... 总算了解!宁夏欢乐划水辅助,微信小程序中至上饶510k辅助器,详细攻略(有挂助手)1、操作简单,无需...
我来教教大家!微信小程序游戏破... 您好,微信小程序游戏破解微乐游戏这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...