Angular 角度测试路由器事件,如NavigationEnd
我从最近两天开始搜索模拟路由器事件,以便进行测试Angular 角度测试路由器事件,如NavigationEnd,angular,testing,routes,Angular,Testing,Routes,我从最近两天开始搜索模拟路由器事件,以便进行测试 window.scrollTo(0,0); 在该区块中: ngOnInit(){ this.router.events.subscribe((evt)=>{ 如果(!(导航结束的evt实例)){ 返回; } 滚动到(0,0); if(this.object.attribute1){ this.loadSomething(); } if(this.object.attribute2){ this.loadSomething2(); } }); }
window.scrollTo(0,0);
在该区块中:
ngOnInit(){
this.router.events.subscribe((evt)=>{
如果(!(导航结束的evt实例)){
返回;
}
滚动到(0,0);
if(this.object.attribute1){
this.loadSomething();
}
if(this.object.attribute2){
this.loadSomething2();
}
});
}
所以我需要在测试中模拟:this.router.events.subscribe((evt)
我已经对此window.scrollTo进行了测试(仅当window.scrollTo不在路由器事件中时有效):
it('调用window.scrollTo',()=>{
expect(component.toBeDefined();
const req=httpTestingController.expectOne(端点);
expect(req).toBeDefined();
expect(request.method).toEqual('GET');
要求冲洗(模拟);
fixture.detectChanges();
expect(spyScrollTo).tohavebeincall();
});
我发现了很多例子,但没有任何帮助,我从来没有理解过这些例子
如果有人得到解释或例子,我会非常感谢
谢谢:)您必须模拟路由器并提供事件对象 大概是这样的:
describe('YourComponent', () => {
let component: YourComponent;
let fixture: ComponentFixture<YourComponent>;
let eventsStub = new BehaviorSubject<any>(null);
let routerStub = {
events: eventsSub,
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
YourComponent,
],
providers: [
// merge the two mocks like this !!
{ provide: Router, useValue: routerStub },
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParams: of({})
},
queryParams: of({}),
queryParamMap: of({}),
params: of({id: 'something'})
},
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
let mockNav = new NavigationEnd(1, 'any', 'any');
// make events have the mockNav listed above
eventsSub.next(mockNav);
// this detectChanges will make ngOnInit be called
fixture.detectChanges();
});
it('calls window.scrollTo', () => {
expect(component).toBeDefined();
expect(spyScrollTo).toHaveBeenCalled();
// your other tests
});
});
这看起来像是我曾经尝试过的东西,但它打破了我以前的测试,我会更深入地检查,Thx:)检查我的编辑,你可以像这样合并两个模拟。您的组件似乎既依赖于
路由器
又依赖于激活的路由
,因此您可以像上面我向您展示的那样模拟它们。如果您向我展示您的整个测试和组件,我想我可以更好地帮助您。这正是我正在做的:/我将向您展示我的每个测试之前和其中一个测试
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0);
console.log('After scrollTo!!!'); // !! remove when done but make sure you see this
if (this.object.attribut1) {
this.loadSomething();
}
if (this.object.attribut2) {
this.loadSomething2();
}
});
}