首页 > 解决方案 > 为帖子编写业力测试用例并以 Angular 8 获得服务

问题描述

我是 Karma 的新手,不知道如何为 POST 方法编写测试用例。

这是我的 service.ts 文件:-

constructor(private httpclient: HttpClient) { }


  url = 'http://localhost:8047/some_url';

  check: Check[];

  public newBehaviour = new BehaviorSubject<Check[]>([]);

  postRents(hire, bookingId, trackingId): Observable<Check> {
    hire.bookingId = bookingId;
    hire.trackingId = trackingId;
    return this.httpclient.post<Check>(this.url, hire, {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      })
    }).pipe(
      tap(data => {
        this.check.push(hire);
        this.newBehaviour.next(this.check);
        console.log(data);
      })
    );

如何测试此代码的 POST ?

编辑:-无法为此测试 POST

postRents(hire, bookingId, trackingId): Observable<Check> {
        hire.bookingId = bookingId;
        hire.trackingId = trackingId;
        return this.httpclient.post<Check>(this.url, hire, {
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          })
        }).pipe(
          tap(data => {
            this.check.push(hire);
            this.newBehaviour.next(this.check);
            console.log(data);
          })
        );

在方法实现中出现错误

it('Check Serivice', () => {

  const mockData: RentBook[] = [{
    rentingId: 343,
    userName: 'dwew',
    phone: 242324,
    bookId: '3442',
    startDate: new Date(),
    endDate: new Date('Wed November 20 2019 00:00:00 GMT+0530 (India Standard Time)'),
   }];

  service.postRents(mockData, bookId: '34', rentId:34).subscribe(
      res => expect(res).toEqual(mockData)
    );
  httpTestingController.expectOne(req => req.url.includes('http://localhost:8047/renting-app/api/v1/rentings') && req.method === 'POST')
      .flush(mockData);
  httpTestingController.verify();
  });

任何传递参数数据的解决方案。不知道如何通过测试用例。

标签: angularkarma-jasmineangular8

解决方案


用于HttpTestingController编写服务测试

  • 导入HttpClientTestingModule您的 TestBed 并使用 TestBedHttpTestingController作为变量注入
  • 这是一个简单的例子:
let mockHttp: HttpTestingController
TestBed.configureTestingModule({
  imports: [HttpClientTestingModule],
  ...
})
mockHttp = TestBed.get(HttpTestingController);

describe('...', () => {
  it('...', () => {
    yourService.funcWhatToTest().subscribe(
      res => expect(res).toEqual(yourMockData);
    )
    mockHttp.expectOne(req => req.url.includes('yourUrl') && req.method == 'POST' && ...)
      .flush(yourMockData);
    mockHttp.verify();
  }
})
  • 这个测试网上会有很多资源。用关键字搜索HttpTestingController

推荐阅读