用角度编写Http服务的测试用例

时间:2018-07-03 03:38:25

标签: angular typescript karma-jasmine angular-unit-test

嗨,我一直在尝试为我的注册服务编写测试用例。它有一个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 },
      ]
    });
  });

我知道不多,我只定义了模拟后端,但会有所帮助

谢谢

1 个答案:

答案 0 :(得分:2)

要开始测试对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匹配。如果没有请求或多个请求与该URL expectOne()匹配,则会抛出该异常。

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

了解有关测试使用HttpClient的角度服务和测试official angular documentation中的Http请求的更多信息。

为您服务。导出界面。

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

但是我建议您将数据模型移动到其他目录或文件中。

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

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