angular-订阅Observable不会返回任何内容

时间:2018-08-17 07:09:27

标签: angularjs typescript observable

我正在编写用于简单服务的单元测试。该服务从后端REST API获取用户列表。

// user.service.ts
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {environment} from '../../../environments/environment';
import {ListDto} from '../../dto/commons/list.dto';

@Injectable()
export class UserService {

  constructor(
    private http: HttpClient
  ) { }

  getUserList(): Observable<ListDto> {
    return this.http
      .get<ListDto>(environment.coreUrl + environment.basePath + '/user');
  }

在单元测试中,我尝试记录Observable返回的getUserList(),但是似乎没有任何输出。我无法执行任何验证,因为未返回任何内容。这是我的单元测试:

// user.service.spec.ts
import {UserService} from './user.service';
import {inject, TestBed} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';

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

  afterEach(inject([
    HttpTestingController
  ], (httpMock: HttpTestingController) => {
    httpMock.verify();
  }));

  it('should be able to get the list of users',
    inject(
      [HttpTestingController, UserService],
      (httpMock: HttpTestingController, service: UserService) => {
        service.getUserList().subscribe((data) => {
          console.log(data); // no output
        });
        // sanity
        const req = httpMock.expectOne('http://localhost:8080/v1/api/user');
        expect(req.request.method).toEqual('GET');
      }
    )
  );

我对Angular很陌生,所以我在某个地方一定是错的。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

当然不会返回任何内容,因为您没有告诉模拟的Http Client返回任何内容。

您需要致电req.flush(someTestData)来进行操作,如the guide所述和所示。