单元测试Angular 5上的http服务

时间:2018-05-29 10:58:06

标签: angular unit-testing

我对如何测试数据服务感到非常困惑,有太多的可能性,而且压倒性的。

我有这个简单的服务:

@Injectable()
export class DataService {

  constructor(private _http: HttpClient) { }

  getData<T>(path: string): Observable<T> {
    return this._http.get<T>(path);
  }

}

我想测试调用getData<number>,实际上会返回number的数据类型。

angular testing guide 令人沮丧地显示了几种方式(使用testbed,使用beforeEach,使用jasmine而不使用testBed)我尝试了所有这些但是没有取得多大成功。

我该怎么做?到目前为止,我甚至未能调用getData。我希望能够模拟Http,发出模拟返回值(如在jasmine.spy.and.returnValue(mockData)中)并验证dataService是否正常

我在data.service.spec.ts

中有这个
describe('DataService', () => {

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [
        HttpClientModule
      ],
      providers: [
        DataService,
        HttpClient
      ]
    });

  });

  // This was auto generated, and works
  it('should be created', inject([DataService], (service: DataService) => {
    expect(service).toBeTruthy();
  }));

  // I added this, but doesn't work
  describe('When getData() is called', () => {

    it('should return an observable of type T', inject([DataService], (service: DataService) => {

      service.getData<number>('mock-url')
        .subscribe(data => {
          expect(typeof(data)).toBe('number');
        });

    }));

  });

});

当我说它不起作用时......第二次测试通过了!但它不应该。我可以看到真实的请求在开发控制台上发送到(无效的)url,并且错误按预期排出,但测试刚刚通过......

所以我想,我的问题很简单,在Angular 5中,我如何模拟我的后端服务并对其进行单元测试呢?

1 个答案:

答案 0 :(得分:3)

尝试使用flush方法测试它

 inject(
  [HttpTestingController, DataService],
  (httpMock: HttpTestingController, service: DataService) =>{
     const mockResponse = 5;
     const mock-url = '...';

     service.getData<number>('mock-url').subscribe(data => {
        expect(data).toEqual(mockResponse);
         expect(typeof(data)).toBe('number');
    });

    const mockRequest = httpMock.expectOne((req: HttpRequest<any>) => req.url === mock-url); //get your request here

    expect(mockRequest.request.method).toBe('GET');

    mockRequest.flush(mockResponse);
   })