【问题标题】:Unit testing http service on Angular 5Angular 5 上的单元测试 http 服务
【发布时间】:2018-05-29 10:58:05
【问题描述】:

我对如何测试数据服务感到很困惑,有太多的可能性,而且让人不知所措。

我有这个简单的服务:

@Injectable()
export class DataService {

  constructor(private _http: HttpClient) { }

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

}

我想测试一下,调用getData&lt;number&gt; 实际上会返回number 的数据类型。

angular testing guide 令人沮丧地展示了几种方法(使用 testbed、使用 beforeEach、使用没有 testBed 的 jasmine),我已经尝试了所有这些方法,但都没有多大成功。

请问我该怎么做?到目前为止,我什至无法拨打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 中,我该如何模拟我的后端服务并对其进行单元测试?

【问题讨论】:

    标签: angular unit-testing


    【解决方案1】:

    尝试使用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);
       })
    

    【讨论】:

    • 嗨 - 谢谢。我收到httpMock.expectOne is not a function 错误。调用前需要初始化吗?
    • 您是否在您的 TestBed.configureTestingModule 中添加了 HttpClientTestingModule ?
    • 是的!它被添加到 providers 数组中!
    • 嗨,这在我从提供商处删除 HttpClient, HttpTestingController 后开始工作。从这里找到:stackoverflow.com/a/45482697/435867
    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 2019-05-06
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多