如何解决角度e2e测试-在OnInit执行之前检查模板
在Angular 9应用程序中,我拥有的组件
ngOnInit(): void {
this.records$ = this.service.loadRecords();
}
loadReords()
返回以null
开头的Observable,然后在Http请求完成后发出记录列表。
在模板中有条件,如果records$
为null,则在更改记录列表-记录表时,可以看到所谓的'loading'div。
当我尝试在page.navigateto();
之后用量角器对其进行测试(e2e)时,会返回:
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();
}));
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。