代码之家  ›  专栏  ›  技术社区  ›  redOctober13

角度服务测试-如何返回预期值?

  •  -1
  • redOctober13  · 技术社区  · 6 年前

    我想知道如何测试服务,以及 docs 参考此 StackBlitz example .

    我不能理解 怎样 ,在 it('should return expected heroes (called once)' 测试断言是否通过。我看不到有任何模仿或间谍准备回来 expectedHeroes getHeroes() 服务上的函数被调用,那么这是如何发生的呢?

    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);
        });
      });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Ian MacDonald    6 年前

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

    当你打电话 getHeroes() ,您将获得一个可观察的对象,该对象将在以后的某个日期通过 subscribe 处理程序。“以后的日期”是你考试的最后一行。

    这个 httpTestingController 正在(大概)跟踪由 TestBed ,但没有响应。获取请求对象时(使用 expectOne ,然后您就可以像远程服务器一样操作并填充响应。

    这个测试是测试 req.flush(expectedHeroes) 适当冲洗 英雄服务 从另一边出去( 订阅 )无需修改。