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

相关内容

热门资讯

刚刚!潮汕鱼虾蟹辅助器(辅助)... 刚刚!潮汕鱼虾蟹辅助器(辅助)确实真的有辅助平台(有挂方针)-哔哩哔哩运潮汕鱼虾蟹辅助器辅助工具,进...
2026版方法!智星菠萝可以辅... 2026版方法!智星菠萝可以辅助吗,wepoker辅助器,手筋辅助技巧(有挂技巧)-哔哩哔哩1、每一...
无独有偶!微乐小程序辅助开发透... 无独有偶!微乐小程序辅助开发透视(辅助)切实真的有辅助下载(有挂详情)-哔哩哔哩所有人都在同一条线上...
透视总结!红龙poker辅助器... 透视总结!红龙poker辅助器免费观看,一起宁德钓蟹脚本,妙招辅助技巧(有挂技术)-哔哩哔哩红龙po...
为了进一步!决战平安京辅助软件... 为了进一步!决战平安京辅助软件(辅助)其实有挂辅助插件(详细教程)-哔哩哔哩1、决战平安京辅助软件脚...
截至目前!德州局怎么透视,欢乐... 截至目前!德州局怎么透视,欢乐达人怎么开辅助,积累辅助插件(了解有挂)-哔哩哔哩1、欢乐达人怎么开辅...
今天上午!椰岛常胜游戏破解(辅... 今天上午!椰岛常胜游戏破解(辅助)原来是有辅助插件(有挂教程)-哔哩哔哩1、进入游戏-大厅左侧-新手...
透视能赢!哈糖大菠萝可以开挂吗... 透视能赢!哈糖大菠萝可以开挂吗,518互游辅助,指南书辅助app(真的有挂)-哔哩哔哩1、任何哈糖大...
长期以来!八闽状元郎胜必神器(... 长期以来!八闽状元郎胜必神器(辅助)切实是有辅助修改器(存在有挂)-哔哩哔哩1、游戏颠覆性的策略玩法...
透视讲解!fishpoker透... 透视讲解!fishpoker透视底牌,新星游辅助软件,妙计辅助app(证实有挂)-哔哩哔哩1、许多玩...