jeudi 18 avril 2019

HttpTestingController tests for correct x-www-form-urlencoded fields via HttpParams

I'm looking to use HttpTestingController to test that the correct set of fields are included in a POST request that my Service sends via a HttpClient.

web-form.ts

export class WebFormService {

constructor(private httpClient: HttpClient) { }

public submitForm(fields): Observable<any> {
  const headers = new HttpHeaders()
      .set('Content-Type', 'application/x-www-form-urlencoded');
  const body = new HttpParams()
    .set('_to',  environment.FORM_RECIPIENT)
    .set('source', 'mysite');

  for (let key of fields) {
      body.set(key, fields[key]);
  }

  return this.httpClient.post(
    environment.FORM_URL,
    body,
    {headers}
  );
}

web-form.spec.ts

it('sends a POST request via the HttpClient service', () => {
    const testFields = {
      name: 'test contributor',
      message: 'my message',
      email: 'test@tester.com'
    };

    webFormService.submitForm(testFields).subscribe();

    const req = httpTestingController.expectOne(environment.FORM_URL);
    expect(req.request.method).toEqual('POST');
    expect(req.request.headers.get('Content-Type')).toEqual('application/x-www-form-urlencoded');

    // Here I'd like to make assertions about the fields that data being posted.

    req.flush('');
});

The HttpRequest is url-encoding the body on so req.request.body is a properly url-encoded string.

Is there any good option to test without resorting to de-encoding request body and comparing objects?

Aucun commentaire:

Enregistrer un commentaire