繁体   English   中英

Angular 单元测试“SPEC HAS NO EXPECTATIONS”和“error: Timeout”

[英]Angular unit testing "SPEC HAS NO EXPECTATIONS" and "error: Timeout"

我正在尝试为我的帖子 function 编写测试。 这是一个 Angular 应用程序,我正在使用 Karma/Jasmine 进行测试。

这是我的测试:

 it(`should post data`, ()=>{
    const service: ApiService = TestBed.get(ApiService);
    service.sendMessage(data).subscribe(values =>{
      expect(values).toBe('observable value');
    });
  });

这两种方法都“通过”了测试,但都有“SPEC HAS NO EXPECTATIONS”消息。 我为此找到的解决方法是尝试从中获取 promise。 我尝试了两种方法:

添加“完成()”

 it(`should post data`, (done:any)=>{
    const service: ApiService = TestBed.get(ApiService);
    service.sendMessage(data).subscribe(values =>{
      expect(values).toBe('observable value');
      done();
    });
  });

或将整个内容重写为:

it('should post data', inject([ApiService], async (service: ApiService) => {
    const tada = await service.sendMessage(data).toPromise();
    expect(tada).toBe('observable data');
  }));

由于超时,这些调用测试失败。(错误:超时 - 异步 function 未在 5000 毫秒内完成(由 jasmine.DEFAULT_TIMEOUT_INTERVAL 设置)因此,为了解决这个问题,我尝试增加超时。 我用了

jasmine.DEFAULT_TIMEOUT_INTERVAL = 150000;

但即使经过更长的时间,它仍然会超时。 这让我认为这不是正确的解决方案,但我无法找到超出我尝试的答案。 我也尝试过移动部件,比如将 expect() 放在订阅之外,等等。

我不会碰jasmine.DEFAULT_TIMEOUT_INTERVAL属性,因为我认为默认的 5 秒对于单元测试来说已经足够了。

这种方法很好:

it(`should post data`, (done: DoneFn)=>{
    const service: ApiService = TestBed.get(ApiService);
    // !! service.sendMessage is never emitting and therefore never going
    // inside of the subscribe block !!
    service.sendMessage(data).subscribe(values =>{
      expect(values).toBe('observable value');
      done();
    });
  });

该问题作为注释写在单元测试文件中。

如果您可以向我展示服务和整个单元测试文件,我可能会提供帮助。 问题是从sendMessage返回的 observable 永远不会发射。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM