如何在没有模拟和间谍的情况下测试 API?

时间:2021-04-16 22:28:29

标签: angular unit-testing jasmine

有包含2个方法的服务:

Financial Analysis
  ----------------------------
  Total Months: 86
  Total: $38382578
  Average  Change: $-2315.12
  Greatest Increase in Profits: Feb-2012 ($1926159)
  Greatest Decrease in Profits: Sep-2013 ($-2196167)

我尝试编写单元测试:

export class CounterService {
  constructor(private http: HttpClient) {}

  getGirls(): Observable<any> {
    return this.http.get<any>('http://localhost:3000/girls');   // return some JSON
  }

  getObservableValue() {
    return of('observable value');
  }
}

结果测试“测试应该等待 CounterService.getObservableValue”成功,但测试“测试应该等待 CounterService.getGirls”不成功。 >

Jasmine 显示以下消息:

<块引用>

规范没有期望:测试应该等待 CounterService.getGirls

请帮我测试 getGirls() 没有间谍和任何模拟。有可能吗?

1 个答案:

答案 0 :(得分:1)

您必须使用 HttpTestingController 来发送请求。

describe('CounterService', () => {
  let service: CounterService;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [CounterService],
    });
    service = TestBed.inject(CounterService);
    httpTestingController = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    // ensure no outstanding API calls
    httpTestingController.verify();
  });

  it(
    'test should wait for CounterService.getObservableValue',
    waitForAsync(() => {
      service
        .getObservableValue()
        .subscribe((value) => expect(value).toBe('observable value'));
    })
  );

  it(
    'test should wait for CounterService.getGirls',
    waitForAsync(() => {
      service
        .getGirls()
        .subscribe((value) => expect(value).toBeTruthy());

      const req = httpTestingController.expectOne('http://localhost:3000/girls');
      expect(req.request.method).toBe('GET');
      
      // flush this response
      req.flush(['Alicia', 'Tina', 'Michelle']);
    })
  );
});

This 是一篇很好的博客文章,可以帮助您进行 Http 测试。