gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:48:29 24 4
gpt4 key购买 nike

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

ngOnInit(): void {
this.records$ = this.service.loadRecords();
}
loadReords()返回以 null 开头的 Observable然后在 Http 请求完成后发出记录列表。
在模板中有条件如果 records$为 null 所谓的“加载”div 将是可见的,当更改记录列表 - 记录表。
当我尝试在 page.navigateTo(); 之后用 Protractor 测试它 (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();
}));
})

关于Angular e2e 测试 - 在 OnInit 执行之前检查模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64308559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com