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辅助脚本,wpk俱乐部是真的吗,竟然真的有挂(有挂实锤)1、完成有辅助插件,...
分辨真假!wepoker有脚本... 分辨真假!wepoker有脚本吗,拱趴大菠萝开挂方法,一贯真的是有挂(存在有挂);1、用户打开应用后...
实测发现!约局吧游戏挂,wej... 实测发现!约局吧游戏挂,wejoker辅助软件,一贯有挂(有挂教学)1、破解器简单,机器人操作,插件...
玩家必看教程!hhpoker辅... 玩家必看教程!hhpoker辅助器视频,wepoker怎么增加运气,其实真的是有挂(真是有挂)1、辅...
程序员教你!werplan外卦... 程序员教你!werplan外卦神器,hhpoker外挂靠谱吗,果然真的有挂(有挂讲解)1、在插件功能...
玩家必看科普!we-poker... 玩家必看科普!we-poker辅助,wepoker轻量版有透视吗,一直存在有挂(有挂方略)1、首先打...
玩家攻略!wepoker亲友圈... 玩家攻略!wepoker亲友圈有用吗,aapoker怎么控制牌,其实存在有挂(有挂技巧)1、点击下载...
一分钟了解!fishpoker... 一分钟了解!fishpoker透视,htx矩阵wepoker辅助,切实是有挂(确实有挂)1、打开软件...
记者发布!约局吧德州透视,cl... 记者发布!约局吧德州透视,cloudpoker外挂,好像是真的有挂(有挂秘诀)1)有没有挂:进一步探...
如何分辨真伪!悟空黑桃a有挂嘛... 如何分辨真伪!悟空黑桃a有挂嘛,wepokerplus开挂,好像真的是有挂(有挂秘笈)1)辅助插件:...