【问题标题】:angular http service call unit test with params带参数的角度http服务调用单元测试
【发布时间】:2019-12-11 15:22:33
【问题描述】:

我正在尝试测试此服务调用

get(): Observable<Country[]> {
const config = { params: new HttpParams().set('pagesize', '300') };
return this.http
  .get<any>(`${api_url}countries`, config)
  .pipe(map(response => (response.data as Country[]))); }

这是测试:

describe('CountriesService Tests', () => {

let countriesService: CountriesService;
let httpTestingController: HttpTestingController;

let countries: Country[] = [
    { Country: 'ALBANIA', CountryCode: 'AL', ReportingCountryCode: 'ALB' },
    { Country: 'Canada', CountryCode: 'CA', ReportingCountryCode: 'CND' }];
beforeEach(() => {

    TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
        providers: [CountriesService]
    });
    countriesService = TestBed.get(CountriesService);
    httpTestingController = TestBed.get(HttpTestingController);
});
afterEach(() => {
    httpTestingController.verify();
});

it('should return all countries', () => {
    countriesService.get().subscribe((data: Country[]) => {
        expect(data).toBe(countries);
    });
    const url = ({ const: environment.url + 'countries', params: {'pagesize': '300'}});

    let countriesRequest: TestRequest = httpTestingController.expectOne(url.const + url.params);

    expect(countriesRequest.request.method).toEqual('GET');

    countriesRequest.flush(countries);
})});

我收到此错误:错误:预期有一个对条件“匹配 URL:/api/publicdata/countries[object Object]”的匹配请求,但没有找到。 我们关于传递给调用的参数的问题,我不知道如何添加它们。你能帮忙吗?

【问题讨论】:

  • 这可能是一个错字,但服务方法是 get() 但您实际上并没有在测试中调用该特定方法,而是调用 getCountries() 。同样是的,您不能将对象插入到这样的字符串中。使用模板字符串或字符串连接来提取您期望的特定属性。 + '?pagesize' + params.pagesize 或类似的。将其与正在运行的应用程序将 url 转换成的内容相匹配。
  • 这是一个错字谢谢
  • expectOne 与 GET 参数一起使用很痛苦。我发现使用expectOne (angular.io/api/common/http/testing/HttpTestingController) 的matchFn 重载更容易。它接收HttpRequest对象,因此您可以轻松比较基本url和参数值
  • 请举例,我看不到matchFn函数,只能匹配

标签: angular unit-testing jasmine karma-runner


【解决方案1】:

不确定 OP 是否修复了它!

expectOne(url.const + url.params) // Wrong
expectOne(url.const + '?param1=value') // should be that

【讨论】:

    【解决方案2】:

    你可能期待 http 调用之后,试试下面的测试用例

        it('should return all countries', () => {
    
        const url = ({ const: environment.url + 'countries', params: {'pagesize': '300'}});
    
        let countriesRequest: TestRequest = httpTestingController.expectOne(url.const + url.params);
    
        countriesService.getCountries().subscribe((data: Country[]) => {
                expect(data).toBe(countries);
            });
    
        expect(countriesRequest.request.method).toEqual('GET');
    
        countriesRequest.flush(countries);
    })});
    

    【讨论】:

    • 还是同样的错误。这与将参数添加到服务调用中有关。我删除了它可以正常工作的参数,但是由于我们的后端可以通过向调用添加参数来进行各种过滤,因此我需要确保调用符合预期
    • 您可能可以删除参数,因为您只是想期待 http 调用。你也应该嘲笑http调用。还添加以下语句countriesRequest.result([country array]
    【解决方案3】:

    可能我迟到了,但下面的解决方案对你们有用

    1. 在其中创建一个HttpParams 对象和append() 您的所有查询参数。
    2. 创建HttpRequest 对象并为其提供适当的值。
    3. 然后如下图调用httpTestingController.expectOne()
    4. 我使用urlWithParams 来比较网址,因为它减少了检查每个网址的代码 参数对象。
     it('should return all countries', fakeAsync(() => {
    
        countriesService.getCountries().subscribe((data: Country[]) => {
                expect(data).toBe(countries);
            });
         // you can create multiple parameters by appending on same object 
        let parameters = new HttpParams().append('pagesize', '30');
         
        // environment is your base url
        const httpReq = new HttpRequest('GET',environment.url, {params:parameters}); 
    
        let countriesRequest = httpTestingController.expectOne((req:HttpRequest)=>
            req.method === httpReq.method && req.urlWithParams === httpReq.urlWithParams
        );
       
        countriesRequest.flush(countries);
        httpTestingController.verify();
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2019-05-29
      • 1970-01-01
      相关资源
      最近更新 更多