Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpTestingController.expectOne() with queryparameters

I am new to angular testing using Jasmine/Karma. I encountered a problem while testing an angular service using HttpTestingController. Here is a part of the source code :

getProfile(userName: string) {
    let config = {
      params: {
        user_id: "test"    
      }
    }
    return this.http
      .get(`https://api.github.com/users/${userName}`, config);
  }

when calling the service using expectOne of HttpTestingController :

it('should add an Authorization header', () => {
let response;
userService.getProfile('blacksonic').subscribe(response => {
  expect(response).toBeTruthy();    });


const req = 
httpMock.expectOne({ method: 'GET', url:'https://api.github.com/users/blacksonic' });
                   });

I get the following error :

Error: Expected one matching request for criteria "Match method: GET, URL: https://api.github.com/users/blacksonic", found none.
at HttpClientTestingBackend.expectOne (./node_modules/@angular/common/fesm5/http/testing.js?:301:19)
at UserContext.eval (./src/app/Interceptors/Interceptor.spec.ts?:85:28)
at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:387:26)
at ProxyZoneSpec.onInvoke (./node_modules/zone.js/dist/zone-testing.js?:287:39)
at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:386:32)
at Zone.run (./node_modules/zone.js/dist/zone.js?:137:43)
at runInTestZone (./node_modules/zone.js/dist/zone-testing.js?:508:34)
at UserContext.eval (./node_modules/zone.js/dist/zone-testing.js?:523:20)
like image 405
samir Avatar asked Feb 19 '19 16:02

samir


People also ask

What is expectOne in angular?

expectOne()link mode_edit code. Expect that a single request has been made which matches the given URL, and return its mock.

What is HttpClientTestingModule?

Using the HttpClientTestingModule and HttpTestingController provided by Angular makes mocking out results and testing http requests simple by providing many useful methods for checking http requests and providing mock responses for each request.

What is req flush?

flush()link Resolve the request by returning a body plus additional HTTP information (such as response headers) if provided. If the request specifies an expected body type, the body is converted into the requested type. Otherwise, the body is converted to JSON by default.


1 Answers

you are passing a parameter. So something like this will work:

const req = httpMock.expectOne(
 { method: 'GET', url:'https://api.github.com/users/blacksonic?user_id=test' });
like image 94
Normunds Kalnberzins Avatar answered Oct 21 '22 21:10

Normunds Kalnberzins