繁体   English   中英

Angular e2e 测试 - 在 OnInit 执行之前检查模板

[英]Angular e2e testing - check template before OnInit executes

在 Angular 9 应用程序中,我有一个组件

ngOnInit(): void {
  this.records$ = this.service.loadRecords();
}

loadReords()返回以null开头的 Observable,然后在 Http 请求完成后发出记录列表。

在模板中有一些条件,如果records$为空,那么当更改记录列表 - 记录表时,所谓的“加载”div 将是可见的。

当我尝试在page.navigateTo();之后用量角器测试它 (e2e) 时page.navigateTo(); 什么返回:

navigateTo(): Promise<unknown> {
 return browser.get(`${browser.baseUrl}${this.url}`) as Promise<unknown>;
}

我可以遍历已完成的页面(已加载记录 - 甚至有意延迟对这些记录的代理 API 调用)。

我如何遍历以“加载”阶段呈现的页面 - 在records$流加载之前?

您为此使用 e2e 测试而不是更孤立的测试是否有特定原因? 后者将使您能够监视服务的方法并添加延迟,以便您可以在加载状态期间进行断言:

describe('MyComponent', ()=>{
  let fixture: ComponentFixture<MyComponent>;
  let comonent: MyComponent;
  let myService: MyService;
  
  beforeEach(()=>{
    TestBed.configureTestingModule({
       declarations: [MyComponent]
    });
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    myService = TestBed.inject(MyService);
  });

  it('should show the loading <div>', fakeAsync(() => {
    // set up the fake service method with a delay
    const simulatedDelayMS = 500;
    const recordsStub = [{foo: 'bar'}, {foo: 'baz'}, {foo: 'qux'}];
    const recordsStubWithDelay$ = of(recordsStub).pipe(delay(simulatedDelayMS));
    spyOn(myService, 'loadRecords').and.returnValue(recordsStubWithDelay$);

    // perform the first change detection run
    fixture.detectChanges();
    const getLoadingDiv = () => fixture.debugElement.query(By.css('div.loading'))).nativeElement;

    // the <div> should be displayed
    expect(getLoadingDiv()).not.toBeNull();

    // simulate the enough time passing for the data to finish loading
    tick(1000);
    
    // the <div> should no longer be displayed
    expect(getLoadingDiv()).toBeNull();
  }));
})

暂无
暂无

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

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