如何测试 HttpClient 请求

How to test a HttpClient request

我需要测试我的 HttpClient 请求。我有以下测试代码:

import { TestBed, inject } from '@angular/core/testing';

import { AviorBackendService } from './avior-backend.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpEventType, HttpEvent } from '@angular/common/http';
import { User } from '../models/user.model';

describe('AviorBackendService', () => {
  let httpTestingController: HttpTestingController;
  let service: AviorBackendService;

  beforeEach(() => {
   TestBed.configureTestingModule({
     imports: [HttpClientTestingModule],
     providers: [AviorBackendService],
   });

   httpTestingController = TestBed.get(HttpTestingController);
   service = TestBed.get(AviorBackendService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('expects the service to fetch data with proper sorting', () => {
    console.log(service.SERVICE_URL);
    const mockResponse = [{
    _id: 25,
    loginId: 'string',
    lastname: 'string',
    firstname: 'string',
    password: 'string',
    eMail: 'string',
   } as User];

    /*  service.getUserCollection().subscribe(data => {
      expect(data.firstName).toEqual('Namehere');
    });  */
    // const req = httpTestingController
    // .expectOne(req => req.method === 'GET' && req.url === 'http://example.org');
    const req = httpTestingController.expectOne('http://localhost:3000/users');
    expect(req.request.method).toEqual('POST');
    console.log('REQ REQUEST URL:', req.request.url);
    // send the response to the subscribe.
    req.flush(mockResponse as any);
  });
});

问题是 req 测试失败并显示错误消息 Error: Expected one matching request for criteria "Match URL: http://localhost:3000/users", found none. 并且 Property 'firstName' does not exist on type 'User[]'.expect(data.firstName).toEqual('Namehere'); 上被抛出(这就是它被注释掉的原因)。我尝试修改代码,遵循 here 的建议没有帮助。我尝试修改代码但无济于事。

我的用户-collection.model.ts:

import { User } from './user.model';

export interface UserCollection {

    user: User[];

}

我的user.model.ts:

import { Role } from './role';

// was class and not interface!
export interface User {
    _id: number;
    mandator?: number;
    loginId: string;
    lastname: string;
    firstname: string;
    password: string;
    eMail: string;
    group?: string;
    role?: Role;
    active?: boolean;
    token?: string;
}

我的后端代码:

export class AviorBackendService {
  readonly SERVICE_URL = 'http://localhost:3000/';
........
getUserCollection() {
    // withCredentials is very important as it passes the JWT cookie needed to authenticate
    return this.client.get<User[]>(this.SERVICE_URL + 'users', { withCredentials: true });
  }

'firstName' 在类型 'User[]'

上不存在

在用户class中名字属性是小写的,你需要遵循相同的结构。

将 firstName 更改为 firstname;

试试这个,订阅必须取消注释才能使 expectOne 工作。

it('expects the service to fetch data with proper sorting', () => {
    const mockResponse = [{
    _id: 25,
    loginId: 'string',
    lastname: 'string',
    firstname: 'string',
    password: 'string',
    eMail: 'string',
   }];

    service.getUserCollection().subscribe(data => {
      expect(data[0].firstname).toEqual('string');
    });
    const req = httpTestingController.expectOne('http://localhost:3000/users');
    expect(req.request.method).toEqual('GET'); // GET instead of POST
    // send the response to the subscribe.
    req.flush(mockResponse);
  });