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、微乐家乡破解版辅助...
长期以来!wepoker辅助插... 长期以来!wepoker辅助插件功能(透视)游戏黑科技夫追求(一直存在有辅助app)-哔哩哔哩1.游...
透视科技!拱趴大菠萝作必弊方法... 透视科技!拱趴大菠萝作必弊方法(透视)中至赣州黑科技辅助软件(本来有辅助辅助器)-哔哩哔哩1、全新机...
透视智能ai!淘宝买wepok... 透视智能ai!淘宝买wepoker透视有用吗(透视)玩吧辅助脚本(一直是有辅助辅助器)-哔哩哔哩1、...
透视肯定!wepoker辅助器... 透视肯定!wepoker辅助器是真的吗(透视)心悦海南苹果版辅助(原来是真的辅助神器)-哔哩哔哩1、...
一直以来!wepoker钻石怎... 一直以来!wepoker钻石怎么看底牌(透视)丫丫老陕开挂(好像真的是有辅助下载)-哔哩哔哩1、丫丫...
透视实锤!wepoker怎么提... 透视实锤!wepoker怎么提高运气(透视)赣湘互娱挂(都是存在有辅助神器)-哔哩哔哩1、赣湘互娱挂...
透视辅助!newpoker脚本... 透视辅助!newpoker脚本(透视)四川微乐小程序辅助器(都是是真的辅助平台)-哔哩哔哩;一、四川...
为切实保障!哈糖大菠萝攻略(透... 为切实保障!哈糖大菠萝攻略(透视)广东雀神智能插件(本来真的是有辅助安装)-哔哩哔哩所有人都在同一条...
透视好友房!wepoker俱乐... 透视好友房!wepoker俱乐部辅助(透视)广西友乐免费辅助使用视频(切实是有辅助软件)-哔哩哔哩1...