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

相关内容

热门资讯

一分钟模板!德普之星辅助器怎么... 一分钟模板!德普之星辅助器怎么用(透视)其实真的是有辅助脚本(哔哩哔哩)1、点击下载安装,德普之星辅...
第8分钟法子!aapoker辅... 第8分钟法子!aapoker辅助器怎么用(透视)好像是真的有辅助辅助(哔哩哔哩)1、aapoker辅...
两分钟绝活!wepoker数据... 两分钟绝活!wepoker数据分析(透视)好像真的是有辅助教程(哔哩哔哩)1、下载好wepoker数...
第3分钟攻略!拱趴游戏破解器(... 第3分钟攻略!拱趴游戏破解器(透视)总是真的有辅助脚本(哔哩哔哩)1、在拱趴游戏破解器插件功能辅助器...
三分钟练习!德普之星透视软件免... 三分钟练习!德普之星透视软件免费入口官网(透视)切实真的是有辅助脚本(哔哩哔哩)1、三分钟练习!德普...
第四分钟绝活儿!wepoker... 第四分钟绝活儿!wepoker黑侠破解(透视)竟然真的是有辅助安装(哔哩哔哩)1、wepoker黑侠...
十分钟演示!aapoker万能... 十分钟演示!aapoker万能辅助器(透视)果然是真的有辅助教程(哔哩哔哩)1、aapoker万能辅...
第九分钟大纲!德普之星私人局辅... 第九分钟大纲!德普之星私人局辅助器(透视)果然真的是有辅助插件(哔哩哔哩)1、完成德普之星私人局辅助...
九分钟秘籍!pokerrrr2... 九分钟秘籍!pokerrrr2辅助(透视)一贯是有辅助插件(哔哩哔哩)1、pokerrrr2辅助脚本...
第十分钟方针!哈糖大菠萝攻略(... 第十分钟方针!哈糖大菠萝攻略(透视)其实是真的有辅助插件(哔哩哔哩)1、哈糖大菠萝攻略免费辅助多个强...