简体   繁体   English

Angular 5上的单元测试http服务

[英]Unit testing http service on Angular 5

I'm pretty confused about how to test a data service, there's just way too many possibilities and it's overwhelming. 对于如何测试数据服务,我感到很困惑,存在太多的可能性,而且势不可挡。

I have this simple service: 我有这个简单的服务:

@Injectable()
export class DataService {

  constructor(private _http: HttpClient) { }

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

}

I want to test that calling getData<number> will, infact, return a data type of number . 我想测试调用getData<number>实际上将返回number的数据类型。

The angular testing guide frustratingly shows several ways (use testbed, use beforeEach, use jasmine without testBed) and I've tried all of them but not with much success. 角度测试指南令人沮丧地显示了几种方法(使用测试床,使用beforeEach,在没有testBed的情况下使用茉莉花),而我已经尝试了所有方法,但都没有成功。

How do I do this please? 我该怎么做? I have so far failed to even get as far as calling the getData . 到目前为止,我什至无法调用getData I want to be able to mock the Http, emit mock return values (like in jasmine.spy.and.returnValue(mockData) ) and verify that dataService is OK 我希望能够模拟Http,发出模拟返回值(例如jasmine.spy.and.returnValue(mockData) ),并验证dataService正常

I've got this in my data.service.spec.ts : 我已经在我的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');
        });

    }));

  });

});

When I say it doesn't work... the second test passes! 当我说这行不通时...第二项测试通过了! but it shouldn't. 但这不应该。 I can see the real request go out on dev console to the (invalid) url, and that errors out as expected, but the test just passes... 我可以看到真正的请求在开发人员控制台上发送到(无效的)url,并且该错误按预期进行,但是测试只是通过...

So I guess, my question is simply, in Angular 5, how do I mock my backend service and unit test it please? 所以我想,我的问题很简单,在Angular 5中,如何模拟后端服务并对其进行单元测试?

try to test it like this using flush method 尝试使用冲洗方法像这样测试

 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);
   })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM