mardi 17 juillet 2018

Angular 5 return mock HTTP response to service being tested

Please excuse my ignorance, I am very new to Angular.

In my current situation, I have a service with a function that makes an http call, and returns true or false depending on the payload of the request. The issue is that I don't want to mock what the function returns (true or false) I just want to mock the HTTP response, and let the function decide if that means its true or false.

service.ts

dothing(a: string, b: string): Observable<boolean> {
 return this.http.post('/route/', {'a': a, 'b': b})
   .map((payload => {
     if(payload['thingImLookingFor']) {
       return true;
     } else {
       return false;
     } 
  }
}

service.spec.ts

it('should call dothing via http post', () => {
  inject([Service, HttpTestingController, HttpClient],
    (service: Service, backend: HttpTestingController, http: HttpClient) => {

    service.login('foo', 'bar').subscribe((next) => {
      console.log('We Never Reach Inside Here Because I Never Log And The Test Passes');
      expect(next).toEqual(true);
    });

    const req = backend.expectOne('/route/');

    req.flush({
        error: '',
        thingImLookingFor: false
      });
  });
});

I want to fake the HTTP response within the function, but I want my function to still pick it apart and decide if it has what I'm looking for, because that's the functionality I'm trying to make sure works. How would I do that?

I tried splitting it into multiple functions, but it ended up really ugly and essentially resulted in an entire rewrite of the workflow this function is a part of. I can and will do it if that's the only way, but I want to make sure I'm not missing an easier solution

Aucun commentaire:

Enregistrer un commentaire