首页 > 解决方案 > 如何在 Angular 7 中测试服务

问题描述

我想测试从我的服务收到的数据。我阅读了角度文档并遵循了 observable 示例,但是当我订阅 observable 时我没有收到任何数据。Console.log() 在订阅中不起作用。

该服务工作正常,并在真实环境中获取正确的数据。

我尝试使用 async 和 doneFn 但他们都没有工作,他们都超时了。

服务文件

export class BackService {

  URL = '********'; // I removed url for security.

  constructor(private httpClient: HttpClient) { }

  getAllForms(): Observable<Array<object>> {
    return this.httpClient.get<Array<object>>(`${this.URL}/allForms`);
  }

  getFormById(formId): Observable<Array<object>> {
    return this.httpClient.get<Array<object>>(`${this.URL}/form/${formId}`);
  }
}

测试服务文件

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


describe('BackService', () => {
  let httpMock: HttpTestingController;
  let backService: BackService;
  beforeEach(() => {
    TestBed.configureTestingModule({
    imports: [ HttpClientTestingModule ],
    providers: [BackService]
    });
    backService = TestBed.get(BackService);
    httpMock = TestBed.get(HttpTestingController);
  });
  it('should be created', () => {
    expect(backService).toBeTruthy();
  });
  describe('Methods', () => {
    describe('All Forms', () => {
      it('should use GET method', () => {
        backService.getAllForms().subscribe();
        const req = httpMock.expectOne(`${backService.URL}/allForms`);
        expect(req.request.method).toBe('GET');
      });
      it('should use the right url', () => {
        backService.getAllForms().subscribe();
        const req = httpMock.expectOne(`${backService.URL}/allForms`);
        expect(req.request.url).toBe(`${backService.URL}/allForms`);
      });
      it('should return the right data', () => {
        const mockData = [{'_id': 435345345, '_type': 'window'}]
        backService.getAllForms().subscribe(data => {
          expect(data).toEqual(mockData);
        });
      });
    });
  });

标签: javascriptangularunit-testing

解决方案


前 2 个测试看起来没问题,对于第三个测试来接收您可以测试的数据,您必须通过使用您希望 httpClient 返回的必要对象调用其 flush() 方法来触发该“httpMock”。

这应该适用于第三次测试:

it('should return the right data', () => {
    const mockData = [{'_id': 435345345, '_type': 'window'}]
    backService.getAllForms().subscribe(data => {
      expect(data).toEqual(mockData);
    });
    const req = httpMock.expectOne(`${backService.URL}/allForms`);
    req.flush(mockData);
});

推荐阅读