我正在寻找使用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编码的字符串。
有什么好的选择可以进行测试而无需对请求主体进行解码和比较对象?
慕容森
相关分类