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插件,wpk有... 透视有挂!wpk插件,wpk有那种辅助吗(透视)一直真的是有脚本(哔哩哔哩)1、金币登录送、破产送、...
现有关情况通报如下!wepok... 现有关情况通报如下!wepoker怎么提高运气,微乐游戏竞技团辅助,揭露透视(的确有挂)-哔哩哔哩1...
备受关注的!wepoker免费... 备受关注的!wepoker免费脚本咨询,微信微乐辅助器免费,开挂脚本(有挂方法)-哔哩哔哩;wepo...
脚本总结!wpk有辅助器吗,w... 脚本总结!wpk有辅助器吗,wpk系统是否存在作必弊行为(透视)其实是真的挂(哔哩哔哩);1、实时透...
突发!wepoker透视器免费... 突发!wepoker透视器免费,微乐自建房脚本下载,开挂透视(有挂分析)-哔哩哔哩1、游戏颠覆性的策...
透视诀窍!aapoker辅助怎... 透视诀窍!aapoker辅助怎么用,AApoker辅助工具一直存在有脚本,第5分钟教程(有挂神器)1...
记者获悉!wepoker辅助器... 记者获悉!wepoker辅助器怎么弄,微乐小游戏万能修改器,揭露脚本(证实有挂)-哔哩哔哩1、打开软...
透视曝光!德普之星辅助器app... 透视曝光!德普之星辅助器app,德普之星怎么设置埋牌(透视)切实是有app(哔哩哔哩)1、这是跨平台...
透视有挂!wepokerplu... 透视有挂!wepokerplus透视脚本免费,微乐小程序黑科技辅助工具2026最新推荐,揭幕透视(有...
透视有挂!wepoker怎么破... 透视有挂!wepoker怎么破解游戏,wejoker辅助软件视频(透视)一贯有工具(哔哩哔哩)是不是...