在Angular 9中测试带参数的HTTP POST请求,你需要使用Angular的测试工具,包括@angular/common/http/testing
模块和jasmine
测试框架。以下是详细的步骤和示例代码:
以下是一个在Angular 9中测试带参数的HTTP POST请求的示例:
// my-service.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private http: HttpClient) {}
postData(data: any): Observable<any> {
return this.http.post('/api/data', data);
}
}
// my-service.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { MyService } from './my-service.service';
describe('MyService', () => {
let service: MyService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [MyService]
});
service = TestBed.inject(MyService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('should post data to the server', () => {
const dummyData = { key: 'value' };
const expectedResponse = { success: true };
service.postData(dummyData).subscribe(response => {
expect(response).toEqual(expectedResponse);
});
const req = httpMock.expectOne('/api/data');
expect(req.request.method).toBe('POST');
expect(req.request.body).toEqual(dummyData);
req.flush(expectedResponse);
});
});
通过以上步骤和示例代码,你可以在Angular 9中测试带参数的HTTP POST请求。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云