首页 > 解决方案 > Angular 服务测试 - 如何返回预期值?

问题描述

我试图弄清楚如何测试服务,文档引用了这个StackBlitz 示例

在断言通过的测试中,我无法理解当调用服务上的函数时,it('should return expected heroes (called once)'我没有看到任何模拟或间谍设置返回,那么这是怎么回事?expectedHeroesgetHeroes()

describe('#getHeroes', () => {
    let expectedHeroes: Hero[];

    beforeEach(() => {
      heroService = TestBed.get(HeroesService);
      expectedHeroes = [
        { id: 1, name: 'A' },
        { id: 2, name: 'B' },
       ] as Hero[];
    });

    it('should return expected heroes (called once)', () => {
    //------------------------------------------
    // HOW IS THIS PASSING???

      heroService.getHeroes().subscribe(
        heroes => expect(heroes).toEqual(expectedHeroes, 'should return expected heroes'),
        fail
      );

      // HeroService should have made one request to GET heroes from expected URL
      const req = httpTestingController.expectOne(heroService.heroesUrl);
      expect(req.request.method).toEqual('GET');

      // Respond with the mock heroes
      req.flush(expectedHeroes);
    });
  });

标签: angularunit-testing

解决方案


我不知道它的实现HeroesService是什么,但我想我可以根据测试体的其余部分做出一个很好的猜测。

当您调用 时getHeroes(),您将获得一个可观察对象,该对象将在以后通过subscribe处理程序实现。“较晚的日期”作为测试的最后一行出现。

httpTestingController是(大概)跟踪由 中的事物发出的所有 HTTP 请求,TestBed但不响应它们。当您获取请求对象(使用expectOne)时,您就可以充当远程服务器并填充响应。

该测试是在没有修改的情况下req.flush(expectedHeroes)正确地HeroesService从另一侧 ( ) 冲出和冲出的测试。subscribe


推荐阅读