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

相关内容

热门资讯

传递经验!wepokerplu... 传递经验!wepokerplus外挂(辅助挂)好像是真的有挂(有挂方略辅助app)1、打开软件启动之...
玩家爆料!hhpoker德州有... 玩家爆料!hhpoker德州有挂吗(辅助挂)一直真的有挂(有挂工具辅助教程)一、游戏安装教程牌型概率...
重大通报!fishpoker透... 重大通报!fishpoker透视底牌(辅助挂)切实是有挂(存在有挂辅助软件)1、用户打开应用后不用登...
一分钟揭秘!wepoker养号... 一分钟揭秘!wepoker养号规律(辅助挂)原来是真的有挂(有挂实锤辅助app)1、该软件可以轻松地...
最新技巧!newpoker怎么... 最新技巧!newpoker怎么安装脚本(辅助挂)好像真的有挂(有挂教学辅助方法)1、玩家可以在线上大...
我来教教你!wepoker辅助... 我来教教你!wepoker辅助器是真的吗(辅助挂)一贯是有挂(真实有挂辅助技巧)我来教教你!wepo...
科技通报!哈糖大菠萝可以开挂吗... 科技通报!哈糖大菠萝可以开挂吗(辅助挂)确实真的是有挂(果真有挂辅助软件)1、模拟器是什么优化,俱乐...
科技新动态!hhpoker破解... 科技新动态!hhpoker破解工具(辅助挂)好像是有挂(有挂秘籍辅助攻略);1、每一步都需要思考,不...
实测揭晓!佛手在线大菠萝智能辅... 实测揭晓!佛手在线大菠萝智能辅助器(辅助挂)切实是有挂(的确有挂辅助工具)1、该软件可以轻松地帮助玩...
玩家必看科普!hhpoker德... 玩家必看科普!hhpoker德州透视(辅助挂)其实存在有挂(有挂秘籍辅助技巧)1、让任何用户在无需安...