我试图测试当用户导航到页面时侧边栏中的元素是否正确折叠。我在Jest测试中尝试模拟Angular Router时遇到了麻烦。
我要测试的代码:
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
this.current = event.url;
if (this.current.includes('page1')) {
this._expandMenu(this.page1Toggle);
if (this.current.includes('page2')) {
this._expandMenu(this.page2Toggle);
}
}
this._closeMenu();
});
尝试模拟路由器:
let eventSubject: Subject<Event> = new Subject<Event>();
export class MockRouter {
events: Observable<Event> = eventSubject;
}
测试:
it('should open page1 dropdown if on page1', fakeAsync(() => {
// Arrange
let event = new NavigationEnd(1, '/home/page1', '');
// Act
eventSubject.next(event);
flush();
fixture.detectChanges();
let page1Toggle = fixture.debugElement.query(By.css('#page1Toggle'));
let dropdown = page1Toggle.nativeElement.nextSibling;
// Assert
expect(page1Toggle.attributes['aria-expanded']).toBeTruthy();
expect(dropdown.classList).toContain('show');
}));
我尝试提供路由器{ provide: Router, useClass: MockRouter}
但是在尝试实例化灯具时不断出错:
let fixture: ComponentFixture<SideBarComponent>;
let comp: SideBarComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
SideBarComponent,
],
imports: [
RouterTestingModule
],
providers: [
{ provide: Router, useClass: MockRouter}
]
}).compileComponents();
fixture = TestBed.createComponent(SideBarComponent); --Cannot read property 'root' of undefined
comp = fixture.componentInstance;