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

相关内容

热门资讯

科技揭秘!四川途游小程序辅助,... 科技揭秘!四川途游小程序辅助,hh poker插件下载,透牌教程(有挂教学);详细四川途游小程序辅助...
来一盘!微信小程序透视挂,we... 来一盘!微信小程序透视挂,wepoker黑侠辅助器,德州教程(确实有挂);致您一封信;亲爱微信小程序...
总算了解!爱玩联盟辅助软件视频... 总算了解!爱玩联盟辅助软件视频讲解,破解辅助插件wepoker,揭秘攻略(真的有挂);大家肯定在之前...
每日必看教程!途游手游辅助,p... 每日必看教程!途游手游辅助,pokemmo脚本辅助器,透明教程(有挂教程);人气非常高,ai更新快且...
分享一款!蜀山四川麻亲友房祈福... 分享一款!蜀山四川麻亲友房祈福,竞技联盟辅助插件,辅助教程(存在有挂)是一款可以让一直输的玩家,快速...
分享开挂内幕!胡乐辅助脚本,w... 您好,胡乐辅助脚本这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款...
总算清楚!广西老友玩有破解视频... 总算清楚!广西老友玩有破解视频,we-poker辅助软件教程,wepoke教程(有挂存在);1、这是...
今日重大通报!南宁友乐辅助,w... 今日重大通报!南宁友乐辅助,wepoker作弊辅助,插件教程(有挂辅助);南宁友乐辅助免费下载原版,...
实测分享!皮皮跑胡子系统有鬼,... 实测分享!皮皮跑胡子系统有鬼,epoker透视底牌,wpk教程(有挂技巧);1、选手技艺的积累:德州...
推荐十款!微乐小程序游戏破解器... 推荐十款!微乐小程序游戏破解器下载,德普之星透视,科技教程(存在有挂);人气非常高,ai更新快且高清...