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、任何相约十三水破解ai辅助神器的玩家...
实测交流“竹间茶馆作弊码”aa... 1、实测交流“竹间茶馆作弊码”aa poker辅助(竟然真的有挂)(UU poker、竹间茶馆作弊码...
十分钟了解“杭州都莱挂”详细辅... 十分钟了解“杭州都莱挂”详细辅助普及教程(本来真的有挂)1、进入游戏-大厅左侧-新手福利-激活码辅助...
程序员教你“微乐贵阳足鸡麻将开... 程序员教你“微乐贵阳足鸡麻将开挂”aapoker透视方法(原本是有挂)1、许多玩家不知道微乐贵阳足鸡...
十分钟辅助“微信小程序里的微乐... 十分钟辅助“微信小程序里的微乐可以开挂吗”详细辅助必赢教程(其实有挂);1、实时微信小程序里的微乐可...
一分钟快速了解“上游辅助器”黑... 这是一款非常优秀的上游辅助器 ia辅助检测软件,能够让你了解到上游辅助器中牌率当中全部隐藏参数,与同...
七分钟辅助器“广西八一字牌辅助... 七分钟辅助器“广西八一字牌辅助”详细辅助AI教程(原来是有挂);1、广西八一字牌辅助机器人多个强度级...
科技新动态“新广西老友麻将开挂... 科技新动态“新广西老友麻将开挂”菠萝辅助器免费版的特点(原先有挂)关于新广西老友麻将开挂机制的,其中...
第五分钟辅助器“牌乐门黑科技”... 第五分钟辅助器“牌乐门黑科技”详细辅助解密教程(一贯存在有挂)1、牌乐门黑科技透视辅助简单,牌乐门黑...
我来分享“湛江吴川0759程序... 我来分享“湛江吴川0759程序”hh poker插件下载(果然有挂);玩家必备必赢加哟《136704...