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

相关内容

热门资讯

最新通报!微乐小程序家乡自建房... 最新通报!微乐小程序家乡自建房辅助app,微乐如何自己建脚本-原来真的有辅助插件(有挂解密)1、不需...
记者发布!微信微乐小程序辅助器... 记者发布!微信微乐小程序辅助器免费安装,微乐小程序辅助开发-好像存在有辅助器(有挂方法)1、微信微乐...
今日焦点!微乐小程序辅助工具,... 今日焦点!微乐小程序辅助工具,微乐云南小程序修改器ios-一贯是有辅助器(真是有挂)1、微乐小程序辅...
六分钟了解!微乐陕西小程序破解... 六分钟了解!微乐陕西小程序破解器,微乐小程序辅助器出租-都是真的有辅助脚本(真的有挂)进入游戏-大厅...
实测必看!微乐家乡麻辣自建房辅... 实测必看!微乐家乡麻辣自建房辅助app,万能透视辅助器免费版-真是真的有辅助方法(有挂方法)1、下载...
总算了解!微乐小程序脚本工具平... 总算了解!微乐小程序脚本工具平台,微乐小程序免费黑科技下载-本来有辅助软件(有挂方式)1)微乐小程序...
终于知道!微乐小程序微乐辅助软... 您好,微乐小程序微乐辅助软件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】...
我来分享!微乐小程序免费工具,... 我来分享!微乐小程序免费工具,微乐小程序免费黑科技在线下载-竟然存在有辅助技巧(有挂规律)进入游戏-...
大家学习交流!微乐小程序开挂黑... 大家学习交流!微乐小程序开挂黑科技,微乐自建房辅助入口官网-本来存在有辅助方法(确实有挂)1、大家学...
重大来袭!微信微乐小程序辅助器... 重大来袭!微信微乐小程序辅助器免费安装,微信小程序微乐辅助免费-本来是真的有辅助神器(揭秘有挂)微信...