我得到的错误是“ TypeError:无法读取null的属性'routeConfig'”
我正在导入“ RouterTestingModule”,但似乎有些错误,不确定是什么问题。
有人遇到这个问题吗?
代码
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
import { MyService } from '../services/my-service/my.service';
import { RouterTestingModule } from '@angular/router/testing';
// mock the service
class MockMyService extends MyService {
// mock everything used by the component
};
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [ MyComponent ],
providers: [{
provide: MyService,
useClass: MockMyService
}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
MyComponent
@Component({
selector: "app-action-bar",
templateUrl: "./action-bar.component.html",
styleUrls: ["./action-bar.component.css"]
})
export class MyComponent implements OnInit, OnDestroy {
subscription: Subscription;
buttons: ActionBarButton[];
messages: string[] = [];
componentId: number;
constructor(
private myService: MyService,
private router: Router
) {
this.componentId = (this.router.routerState.root.firstChild.routeConfig
.data as PageViewModel).Id;
this.buttons = new Array<ActionBarButton>();
this.subscription = this.myService.actionBarShow$.subscribe(data => {
this.setButtons(data);
});
}
ngOnInit() {
this.messages = this.myService.getMessages();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
setButtons(data) {
this.buttons.push(this.createButton(data));
}
createButton(params?: IActionBarButton) {
let button = new ActionBarButton();
button.componentId = params.componentId || button.componentId;
button.type = params.type || button.type;
button.label = params.label || button.label;
button.styleClass = params.styleClass || button.styleClass;
button.func = params.func || button.func;
return button;
}
doAction(button: IActionBarButton) {
button.func();
}
答案 0 :(得分:1)
您的错误来自这里:
this.router.routerState.root.firstChild.routeConfig.data
您确实已经导入了路由器测试模块,但是不要期望它会根据您的特定需求进行设置。
为避免这种情况,您可以在beforeEach
函数中添加自定义配置:
RouterTestingModule.withRoutes([] as Route[], {} as ExtraOptions);
只需用适合您的测试用例的值替换参数。