如何通过测试Angular 7访问可观察的数据

时间:2019-02-12 17:46:18

标签: angular testing httprequest karma-runner

我正在Angular 7中制作一个应用程序,该应用程序向json服务器发出http请求(获取),然后json服务器返回数据。

我的服务是:

getMembers():Observable<IMember[]> {
    return this.http.get<IMember[]>(url);
}
我可以订阅的

service.getMembers().subscribe(data => {
  this.members = data;
  console.log("Called 'getMembers'");
  console.log(this.members);
});

当我订阅该服务并打印数据时:

Called 'getMembers'
Array(496)
0:
id: "496.000"
name: "John Titor"
group: "D"
url: "https://myprofile/"
memberNum: "fakenum1"

... And goes like this till the end of the returned data ....

495:
id: "1.000"
name: "Carl Sagan"
group: "M"
url: "https://myprofile/"
memberNum: "fakenum495"

我正在尝试使用httpClientTestingModule测试服务:

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

import { MemberService } from './member.service';

//An interface for the returned data
import { IMember } from './imember'

describe('MemberService', () => {

  let injector: TestBed;
  let service: MemberService;
  let httpMock: HttpTestingController;
  let typeMember: IMember[];
  //let members;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
      providers: [MemberService, HttpTestingController]
    });
    injector = getTestBed();
    service = injector.get(MemberService);
    httpMock = injector.get(HttpTestingController);

    //Getting the data from the service 
    service.getMembers().subscribe(data => {
      var members = data;
    });
  });

  //This test success
  it('should be created', inject([MemberService], (service: MemberService) => {
    expect(service).toBeTruthy();
  }));

  //This test returns an error
  it('should return an Observable<IMember[]>', (members) => {
    let type1 = typeof(members);
    let type2 = typeof(typeMember);
    expect(typeof(type1)).toEqual(typeof(type2));
  });

  //This test returns an error too
  it('first id should equal to 496.00', (data) => {
    expect(data[0].id).toBe("496.00");
  });

});

问题是,当我尝试使用业力(ng test)运行这些测试时,它返回:

MemberService should return an Observable<IMember[]>
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

MemberService first id should equal to 496.00
TypeError: Cannot read property 'id' of undefined

如您所见,Karma无法从可观察对象返回的数据中读取ID(实际上是有效的),我尝试以另一种方式运行此测试(未在beforeEach中初始化服务):< / p>

it('first id should equal to 496.00 V2', () => {
    service.getMembers().subscribe(data => {
        let myMembers = data;
        expect(myMembers[0].id).toBe("9999.00");
    });
});

但是,尽管我实际上设置了一个不可能的测试用例,但Karma表示该测试是成功的(如果我对“应该返回一个Observable”执行相同的情况,则无法识别“期望语句”)。 / p>

我在这里想念的是什么?我试图将服务移至beforeEach部分,因为我怀疑业力不能很好地识别期望语句,因为它位于订阅服务部分内。

有人可以帮助我吗?:(

0 个答案:

没有答案