【问题标题】:How to test a HttpClient request如何测试 HttpClient 请求
【发布时间】:2020-02-05 12:08:03
【问题描述】:

我需要测试我的 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 的建议并没有帮助。我尝试修改代码无济于事。

我的 user-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 });
  }

【问题讨论】:

  • 如果您在实际应用程序中使用,AviorBackendService 是否会返回用户列表?

标签: angular typescript unit-testing karma-jasmine


【解决方案1】:

试试这个,订阅必须取消注释,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);
  });

【讨论】:

    【解决方案2】:

    “用户[]”类型上不存在“名字”

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

    把名字改成名字;

    【讨论】:

    • 这显然使它与 firstname 抛出了同样的错误:/
    • 你必须做expect(data[0].firstname).toBe('string')。响应是一个数组,而不是一个字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 2016-11-03
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多