HttpTestingController通过HttpParams测试正确的

我正在寻找使用HttpTestingController来测试我的服务通过HttpClient发送的POST请求中是否包含正确的字段集。


网络表格


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('');

});

HttpRequest是url编码的body,所以req.request.body是正确的url编码的字符串。


有什么好的选择可以进行测试而无需对请求主体进行解码和比较对象?


catspeake
浏览 235回答 1
1回答

慕容森

实际上,该HttpParams对象仍然可以通过HttpRequestbody属性使用。这有点令人困惑且难以发现,因为HttpParams.toString()函数执行urlencoding,这反过来又导致测试运行程序发出已编码的字符串。因此,仍然可以利用HttpParams函数来获取被测服务提供给的键和值HttpClient。例如...const req = httpTestingController.expectOne(environment.CONTRIBUTION_FORM_ENDPOINT);expect(req.request.method).toEqual('POST');expect(req.request.headers.get('Content-Type')).toEqual('application/x-www-form-urlencoded');const expectedFormKeys = Object.keys(testFields).concat(['_to', 'source']);expect(req.request.body.keys().sort()).toEqual(expectedFormKeys.sort());// ... and so on
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript