【问题标题】:Angular Service Testing - How is the Expected Value Being Returned?Angular 服务测试 - 如何返回预期值?
【发布时间】:2019-01-09 19:03:19
【问题描述】:

我正在尝试弄清楚如何测试服务,docs 引用了这个StackBlitz example

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

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

【问题讨论】:

  • 在进行 http 调用之前,req.flush(expectedHeroes) 似乎使用 httpTestingController 从 Angular 中更深层次的东西返回 expectedHeroes。所以直接嘲讽的不是getHeroes。然后.subscribe 运行,expect 通过。

标签: angular unit-testing


【解决方案1】:

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

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

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

此测试正在测试req.flush(expectedHeroes) 是否正确地通过HeroesService 并流出另一侧 (subscribe) 而无需修改。

【讨论】:

  • 我不知道为什么我没有注意到req.flush 行之前的评论,但你一定是对的。我只是习惯了它在我的真实代码中的样子,调用subscribe 实际上会创建请求。那和flush 对我来说听起来像是一个清理术语,所以我有点跳过它。但 Angular 文档实际上有一条额外的评论:// Respond with mock data, causing Observable to resolve. // Subscribe callback asserts that correct data was returned. req.flush(testData);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多