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、游戏颠覆性的策略玩法,独创攻略技...
透视分享"wpk辅助... 透视分享"wpk辅助是什么"一贯有辅助app(哔哩哔哩)1、每一步都需要思考,不同水平的挑战wpk辅...
透视揭幕"wepok... 透视揭幕"wepoker脚本"果然真的有辅助工具(哔哩哔哩)透视揭幕"wepoker脚本"果然真的有...
透视科普"约局吧能不... 透视科普"约局吧能不能开挂"一贯存在有辅助方法(哔哩哔哩)运约局吧能不能开挂辅助工具,进入游戏界面。...
透视解谜"wepok... 透视解谜"wepoker脚本下载"其实是真的辅助技巧(哔哩哔哩);1、下载好wepoker脚本下载透...
透视开挂"德州hhp... 透视开挂"德州hhpoker是真的吗"原来有辅助脚本(哔哩哔哩)1、全新机制【德州hhpoker是真...
透视详细"wepok... 透视详细"wepoker智能辅助插件"总是是有辅助攻略(哔哩哔哩)1、每一步都需要思考,不同水平的挑...
透视分享"hhpok... 透视分享"hhpoker免费辅助器"总是是有辅助方法(哔哩哔哩)1、不需要AI权限,帮助你快速的进行...
透视解密"wepok... 透视解密"wepoker辅助器软件下载"竟然真的有辅助攻略(哔哩哔哩)1、全新机制【wepoker辅...
透视开挂"wepok... 透视开挂"wepoker透视脚本"果然真的有辅助器(哔哩哔哩)1、在wepoker透视脚本插件功能辅...