Javascript HttpTestingController通过HttpParams测试正确的x-www-form-Url编码字段
我希望使用HttpTestingController来测试我的服务通过HttpClient发送的POST请求中是否包含正确的字段集 web表单.tsJavascript HttpTestingController通过HttpParams测试正确的x-www-form-Url编码字段,javascript,angular,testing,Javascript,Angular,Testing,我希望使用HttpTestingController来测试我的服务通过HttpClient发送的POST请求中是否包含正确的字段集 web表单.ts export class WebFormService { constructor(private httpClient: HttpClient) { } public submitForm(fields): Observable<any> { const headers = new HttpHeaders() .s
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}
);
}
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是对soreq.request上的body
进行url编码的。body
是正确的url编码字符串
在不使用反编码请求正文和比较对象的情况下,有什么好的测试选项吗?实际上,
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
实际上,
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