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、德普...
更值得关注的是!潮汕馆辅助软件... 更值得关注的是!潮汕馆辅助软件,微乐小程序辅助脚本靠谱的,诀窍教程(竟然有挂)-哔哩哔哩在进入微乐小...
透视好友房!德普之星私人局辅助... 透视好友房!德普之星私人局辅助免费,德普之星透视辅助(透视)确实是真的挂(有挂解惑)-哔哩哔哩德普之...
长期以来!手机游戏辅助脚本工具... 您好,微信开心是按照辅助脚本这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】...
透视脚本!德扑圈透视,德普之星... 透视脚本!德扑圈透视,德普之星透视辅助软件(透视)真是是真的挂(有挂存在)-哔哩哔哩;1、玩家可以在...
围绕透视问题!越悦游戏字牌攻略... 围绕透视问题!越悦游戏字牌攻略,德普之星透视辅助软件,妙招教程(有挂技巧)-哔哩哔哩1、用户打开应用...
透视透视!德普之星辅助器,德扑... 透视透视!德普之星辅助器,德扑圈有透视吗(透视)一直有挂(有挂助手)-哔哩哔哩德扑圈有透视吗破解侠是...
日前!道游科技辅助,微信微乐小... 日前!道游科技辅助,微信微乐小程序有窍门吗,课程教程(有挂工具)-哔哩哔哩1、日前!道游科技辅助,微...
透视教程!德普之星辅助器怎么用... 透视教程!德普之星辅助器怎么用,德普之星怎么开辅助(透视)真是是有挂(有挂教学)-哔哩哔哩所有人都在...
有玩家发现!新畅游插件,越乡游... 有玩家发现!新畅游插件,越乡游义乌透视软件,绝活教程(揭秘有挂)-哔哩哔哩1、进入到越乡游义乌透视软...