Skip to content

HttpTestingController.expectOne() not working with queryparameters #19974

Closed

Description

@lenn3k

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[X] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

Related to #19903
When testing a request that contains query parameters, the test throws 2 errors:

  1. Expected one matching request for criteria "Match URL: ./assets/mock/modules.json", found none.
  2. Expected no open requests, found 1: GET ./assets/mock/modules.json

lgbwi

Appending the paramters to the expected URL does not work either.

Expected behavior

Test failure message should show the full path including parameters.
OR
We should be able to specify expected parameters or ignore all.

Minimal reproduction of the problem with instructions

[example.service.spec.ts]

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { Injector } from '@angular/core';
import { async, TestBed } from '@angular/core/testing';
import { ExampleService } from './example.service';

fdescribe('Create a test suite for the Example Service', () => {
    let injector: Injector;
    let exampleService: ExampleService;
    let httpMock: HttpTestingController;

    beforeEach(() => {
        injector = TestBed.configureTestingModule({
            imports:
                [HttpClientTestingModule],
            providers:
                [ExampleService]
        });
        exampleService = injector.get(ExampleService);
        httpMock = injector.get(HttpTestingController);
    });

    afterEach(() => {
        httpMock.verify();
    });

    it('should not immediately connect to the server', () => {
        httpMock.expectNone({});
    });

    describe('when fetching all stuff', () => {
        it('should make a GET request', async(() => {
            exampleService.getStuff();

            let req = httpMock.expectOne(`./assets/mock/modules.json`);
            expect(req.request.method).toEqual('GET');
            req.flush([]);
        }));
    });
});
[example.service.ts]

import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class ExampleService {

    constructor(private http: HttpClient) {
    }

    getStuff() {
        let params = new HttpParams().append('testparam', 'testvalue')
        return this.http.get('./assets/mock/modules.json', {params}).toPromise().then(value => {
            return value
        })
    }
}

What is the motivation / use case for changing the behavior?

Currently it is impossible to test http requests in a service which contain query parameters.

Environment


Angular version: 4.4.4


Browser:
- [X] Chrome (desktop) version 61.0.3163.100
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 
For Tooling issues:
- Node version: V8.4.0  
- Platform: Windows  

Others:

Activity

  1. lenn3k commented on Oct 27, 2017

    @lenn3k
    Author

    The code in this issue seems to work and the actual bug is related to adding params to the http-request.
    I will investigate further if this is an actual bug or if there is a different cause.

  2. changed the title [-]httpClientTestingModule does not work with toPromise[/-] [+]HttpTestingController.expectOne() not working with queryparameters[/+] on Oct 30, 2017
  3. lenn3k commented on Oct 30, 2017

    @lenn3k
    Author

    Issue related to parameters in the request, not the fact that it returned a promise

  4. reopened this on Oct 30, 2017
  5. textbook commented on Nov 8, 2017

    @textbook
    Contributor

    I just came across the same problem. Fixing the error message would be one improvement, but in my view it would be even better if it matched against request.url rather than request.urlWithParams. I'd rather write:

    const req = httpMock.expectOne({ method: 'GET', url: 'http://example.org' });
    expect(req.request.params.get('foo')).toEqual('bar');
    

    than:

    httpMock.expectOne({ method: 'GET', url: 'http://example.org?foo=bar' });
    

    not least because it avoids any ordering issues when you have more than one parameter.


    A current workaround is to use the request matcher function instead:

    const req = httpMock
        .expectOne(req => req.method === 'GET' && req.url === 'http://example.org');
    
  6. added
    area: common/http
    feature
    on Nov 9, 2017
  7. added this to the Backlog milestone on Jan 23, 2018
  8. 25 remaining items

  9. ruimarques commented on Dec 17, 2019

    @ruimarques

    This is quite annoying, just spent some hours until figuring this should be a bug in expectOne. And here it is.

    @textbook work-around works fine, thank you.

  10. denis111 commented on Jun 4, 2020

    @denis111

    I think something is broken here with toPromise() too. I have a service method which makes two requests and returns promise. For the first request it does (this.api.http is HttpClient):

     const resp = await this.api.http
          .get(
            url,
            {
              observe: 'response',
              headers
            }
          ).toPromise();

    After this line the test fails with that "found none" whether I use request params or not, just:

    service.downloadFile('/any/url').then(res => {
          
        });
        const req = httpMock.expectOne('/any/url');
  11. textbook commented on Jun 4, 2020

    @textbook
    Contributor

    @denis111 it's not obvious to me how you think that relates to this issue. As you say, it's not about whether or not there are query parameters. Putting together a minimal example around the code you've posted, the test passes for me, so you'll need to provide something reproducible.

  12. denis111 commented on Jun 5, 2020

    @denis111

    @textbook Yes, I also did a minimal example and it works, so I compared with real code and in real code I have another await before the request. So this test will fail with this code in a service, for example:

    const _ = await Promise.all([]); // just an example instead of real promise
     const resp = await this.api.http
          .get(
            url,
            {
              observe: 'response',
              headers
            }
          ).toPromise();

    EDIT:
    Nevermind. Wrapping the function in fakeAsync and calling tick() worked!

  13. IgnacioMaestro commented on Mar 5, 2021

    @IgnacioMaestro

    I just came across the same problem. Fixing the error message would be one improvement, but in my view it would be even better if it matched against request.url rather than request.urlWithParams. I'd rather write:

    const req = httpMock.expectOne({ method: 'GET', url: 'http://example.org' });
    expect(req.request.params.get('foo')).toEqual('bar');
    

    than:

    httpMock.expectOne({ method: 'GET', url: 'http://example.org?foo=bar' });
    

    not least because it avoids any ordering issues when you have more than one parameter.

    A current workaround is to use the request matcher function instead:

    const req = httpMock
        .expectOne(req => req.method === 'GET' && req.url === 'http://example.org');
    

    I have tried to improve and clarify this solution.
    I have used as a parameter of the method expectOne an arrow function that always return true in order not to filter the requests by url. Afterwards I have checked the url, the method and the query parameters sent.
    This is my approach:

    const testRequest: TestRequest = httpTestingController.expectOne((req) => true);
    expect(testRequest.request.url).toEqual('http://example.org');
    expect(testRequest.request.method).toEqual('GET');
    expect(testRequest.request.params.get('param1') ).toEqual('param1Value');
    expect(testRequest.request.params.get('param2') ).toEqual('param2Value');
    

    I think that the function exepctOne could not receive any params and not check any url (it would be an easier code change) in order not to send a strange arrow function.
    It could be like this:

    const testRequest: TestRequest = httpTestingController.expectOne();
    expect(testRequest.request.url).toEqual('http://example.org');
    expect(testRequest.request.method).toEqual('GET');
    expect(testRequest.request.params.get('param1') ).toEqual('param1Value');
    expect(testRequest.request.params.get('param2') ).toEqual('param2Value');
    
  14. ajith4u81 commented on Apr 26, 2021

    @ajith4u81

    I came across the same problem. Solved by subscribing to the method first. As a result of calling the method, the open array in the HttpClientTestingBackend is updated
    open [] was always empty when i trigger the tests

    Afterward when httpTestingController.expectOne () is getting called, _match helper function, filter based on the match and it will be a success

      let formatedURL=encodeURI(http://example.org?foo=bar&query=xyz)
    
     service.getStuff().subscribe((retuenType: any) => {
      expect(retuenType).not.toBe(null);
      expect(JSON.stringify(retuenType)).toEqual(JSON.stringify(mockResponse));
    });
    
    const req =   httpTestingController.expectOne(formatedURL);
    req.flush(response);
    

    HttpClientTestingBackend

    Pathmatch method
    pathmatch

  15. added
    feature: under consideration
    on Jun 4, 2021
  16. added
    feature: in backlog
    on Nov 26, 2021
  17. added a commit that references this issue on Jan 31, 2022
    34d14eb
  18. JoostK commented on Jan 31, 2022

    @JoostK
    Member

    Hi folks, I've opened #44917 as a bug fix to improve the reported error.

    I considered some designs to allow matching an URL without its query parameters, but this didn't work out as nicely as I'd hoped to be a viable alternative to using a closure-based matcher.

  19. added a commit that references this issue on Feb 1, 2022
    b4e4617
  20. angular-automatic-lock-bot commented on Mar 4, 2022

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  21. locked and limited conversation to collaborators on Mar 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: common/httpfeaturefeature: in backlogfeature: under considerationstate: has PR

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions