Angular 测试路线:SPEC HAS NO EXPECTATIONS 应该导航到 /tests

Angular testing routes: SPEC HAS NO EXPECTATIONS should navigate to /tests

预期的行为是通过单击我的按钮它应该导航到 /tests。我的问题是我对下面代码的期望没有被阅读。我还在下面的 Karma 中添加了我的输出图片。

  it("should navigate to /tests", () => {
    const location = TestBed.get(Location)
    const buttons = de.queryAll(By.css('button')); 
    const nativeButton: HTMLButtonElement = buttons[1].nativeElement; 
    nativeButton.click(); 
    fixture.detectChanges(); 
    fixture.whenStable().then(() => {
        expect(location.path()).toBe('/tests')
    });
  });

当 运行 "ng test":

您正在尝试使用同步测试流程测试异步操作。在你的测试中 expect(location.path()).toBe('/tests')fixture.whenStable() 被解析之后执行,但是你的函数在此之前完成执行,所以你需要告诉茉莉花等待 fixture.whenStable() 解析。更简单的方法是 return promise,这样 jasmine 就会知道它必须等待它终止规范。

it("should navigate to /tests", () => {
    const location = TestBed.get(Location)
    const buttons = de.queryAll(By.css('button')); 
    const nativeButton: HTMLButtonElement = buttons[1].nativeElement; 
    nativeButton.click(); 
    fixture.detectChanges(); 
    return fixture.whenStable().then(() => {
        expect(location.path()).toBe('/tests')
    });
  });

对于更复杂的场景,您可以使用 async/awaitdoneHere 您可以阅读如何实现它。