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

相关内容

热门资讯

WPK安卓!红龙PoKerap... WPK安卓!红龙PoKerapp透视挂ai,约局吧辅助器,其实真的是有ai透视挂绝活儿所有人都在同一...
WPK官网!AApoker工具... WPK官网!AApoker工具开挂ai,德普之星的辅助工具介绍,本来是真的有ai开挂模板1、德普之星...
WPK多开!德扑之星技巧透视a... WPK多开!德扑之星技巧透视ai,wpk是真的还是假的,本来存在有ai透视诀窍1、下载好wpk是真的...
WPK链接!WPK软件开挂ai... WPK链接!WPK软件开挂ai,菠萝德州透视脚本,本来是有ai开挂方式在进入菠萝德州透视脚本软件靠谱...
WPK多开!微扑克插件透视挂a... WPK多开!微扑克插件透视挂ai,aapoker脚本怎么用,本来有ai透视挂模板1、aapoker脚...
WPK四人!AApokerap... WPK四人!AApokerapp透视ai,拱趴大菠萝辅助神器,真是有ai透视办法;1、游戏颠覆性的策...
WPK多开!WPK教程辅助器a... WPK多开!WPK教程辅助器ai,AApoker中牌率,其实存在有ai辅助器积累AApoker中牌率...
WPK模拟器!WePoKer攻... WPK模拟器!WePoKer攻略辅助器ai,智星德州插件,一直是有ai辅助器模板在进入智星德州插件软...
WPK透视版!菠萝智星德州教程... WPK透视版!菠萝智星德州教程透视ai,aa poker透视软件,真是真的有ai透视手筋1、aa p...
WPK多开!WePoKer技巧... WPK多开!WePoKer技巧辅助ai,哈糖大菠萝可以开挂吗,原来是真的有ai辅助方式1、实时哈糖大...