在 angular 中为 Http 服务编写测试用例

Writing test cases for Http service in angular

您好,我一直在尝试为我的注册服务编写测试用例。它有一个 url 发送 4 个值。服务如下:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'



interface registerResponse {
  success: boolean,
  message: string
}

@Injectable()
export class AuthService {

private _regurl ="http://localhost:3000/api/register"
  constructor(private http: HttpClient) { }



  registerUser(username,email,date,  password) {
   
    return this.http.post<registerResponse>(this._regurl, {
      username,
      email,
      date,
      password
      
     
    })
  }

}

我仍在学习如何编写测试用例,我正在尝试让 registerResponse 工作。

这是我写到现在的内容

import { TestBed, async, inject } from '@angular/core/testing';
import {
  HttpModule,
  Http,
  Response,
  ResponseOptions,
  XHRBackend
} from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { AuthService } from './auth.service';
import { HttpClient } from '@angular/common/http'


describe('RegisterService', () => {

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        { provide: HttpClient, useValue: 'http://localhost:3000/api/register' },
        AuthService,
        { provide: XHRBackend, useClass: MockBackend },
      ]
    });
  });

我知道它不多,我只定义了 mockbackend,但我们会提供任何帮助

谢谢

要开始测试对 HttpClient 的调用,请导入 HttpClientTestingModule 和模拟控制器 HttpTestingController,以及测试所需的其他符号。

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

然后将 HttpClientTestingModule 添加到 TestBed 并继续设置被测服务。

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('RegisterService', () => {

  let service: AuthService;
  let httpMock: HttpTestingController;

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [AuthService]
    });

    service = TestBed.get(AuthService);
    httpMock = TestBed.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  describe('#registerUser tests', () => {
    it('Should return registerResponse by making a POST request to the given url', () => {

      const username = 'username';
      const email = 'email';
      const date = 'date';
      const password = 'password';

      const mockResponse: RegisterResponse = {
        success: true,
        message: 'Successfull'
      };
      service.registerUser(username, email, date, password).subscribe((res) => {
        expect(res).toBe(mockResponse);
      });

      const req = httpMock.expectOne('http://localhost:3000/api/register');
      expect(req.request.method).toBe('POST');
      req.flush(mockResponse);
    });
  });
});

现在在您的测试中发出的请求将到达测试后端,而不是普通后端

此设置还调用 TestBed.get() 来注入模拟控制器,以便在测试期间可以引用它。

以下 expectOne() 将匹配请求的 URL.If 没有请求或多个请求匹配 URL expectOne() 将抛出。

const req = httpMock.expectOne('http://localhost:3000/api/register');

阅读更多关于测试使用 HttpClient 的 angular 服务和测试 official angular documentation 中的 Http 请求的信息。

为您服务。导出接口。

export interface RegisterResponse {
  success: boolean,
  message: string
}

但我建议您将数据模型移动到不同的目录或文件中。

然后像这样将接口导入到tes文件中。

import { RegisterResponse } from 'path-to-interface';