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

相关内容

热门资讯

透视普及"wepok... 透视普及"wepoker模拟器哪个"好像真的是有辅助器(哔哩哔哩)wepoker模拟器哪个透视方法中...
透视解迷"wepok... 透视解迷"wepoker有辅助吗"一直存在有辅助技巧(哔哩哔哩)在进入wepoker有辅助吗软件靠谱...
透视关于"wepok... 透视关于"wepoker透视破解版"确实有辅助器(哔哩哔哩)1、进入游戏-大厅左侧-新手福利-激活码...
透视总结"德州透视插... 透视总结"德州透视插件"好像是真的辅助器(哔哩哔哩)1、首先打开德州透视插件辅助器下载最新版本,在德...
透视透视"pokem... 透视透视"pokemomo辅助软件"总是是有辅助app(哔哩哔哩)1、用户打开应用后不用登录就可以直...
透视有挂"hhpok... 透视有挂"hhpoker真的有透视吗"果然真的有辅助方法(哔哩哔哩)1、不需要AI权限,帮助你快速的...
透视揭幕"wepok... 透视揭幕"wepoker有透视吗"竟然有辅助方法(哔哩哔哩)1、玩家可以在wepoker有透视吗透视...
透视曝光"pokem... 透视曝光"pokemmo辅助脚本"确实真的是有辅助技巧(哔哩哔哩)一、pokemmo辅助脚本游戏安装...
透视关于"wpk辅助... 透视关于"wpk辅助是什么"一直是真的辅助方法(哔哩哔哩)1、wpk辅助是什么免费辅助多个强度级别选...
透视解密"扑克之星辅... 您好,扑克之星辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...