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辅助器安装,w... 透视计算!wpk辅助器安装,wpk脚本下载,最新技巧(有挂教学);1、系统规律教程、辅助透视等服务,...
德扑之星有作弊!wepoke辅... 德扑之星有作弊!wepoke辅助,(WEpoke)都是真的是有挂,详细教程(有挂攻略);德扑之星有作...
wpk发牌逻辑!aapoker... wpk发牌逻辑!aapoker猫腻,(wepoke)竟然是有挂,解密教程(有挂介绍)1、在wpk发牌...
透视科技!wepoker辅助透... 透视科技!wepoker辅助透视软件,aapoker辅助器怎么用,玩家必看教程(有挂攻略)一、aap...
德扑之星辅助器购买!aapok... 德扑之星辅助器购买!aapoker有挂,(wepoKE)一贯是有挂,存在挂教程(有挂技巧)暗藏猫腻,...
透视挂!智星菠萝辅助怎么买,德... 透视挂!智星菠萝辅助怎么买,德普之星透视辅助ios,分享认知(有挂黑科技)辅助器中分为三种模型:软件...
透视科技!aapoker透视脚... 透视科技!aapoker透视脚本,wpk辅助器下载,一起来讨论(有挂详情);辅助器中分为三种模型:软...
德扑ai智能!WePoKe外挂... 德扑ai智能!WePoKe外挂,(wepoKE)切实真的有挂,安装教程(有挂脚本)1、每一步都需要思...
透视黑科技!wpk有脚本吗,w... 透视黑科技!wpk有脚本吗,wpk辅助器安装,重大通报(有挂总结);1、系统规律教程、辅助透视等服务...
德扑之星辅助器购买!微扑克全自... 德扑之星辅助器购买!微扑克全自动机器人,(WEPOke)原来是真的有挂,黑科技教程(有挂攻略);1、...