angular - Angular 6 的 Karma-Jasmine 上的“TypeError:无法读取属性‘routeConfig’ of null”
问题描述
我得到的错误是“TypeError:无法读取属性'routeConfig' of null”
我正在导入“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();
});
});
我的组件
@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();
}
解决方案
您的错误来自这里:
this.router.routerState.root.firstChild.routeConfig.data
您确实已经导入了路由器测试模块,但不要期望它会根据您的特定需求进行设置。
为避免这种情况,您可以在beforeEach
函数中添加自定义配置:
RouterTestingModule.withRoutes([] as Route[], {} as ExtraOptions);
只需将参数替换为适合您的测试用例的值。
推荐阅读
- liquibase - 管理来自不同应用程序的变更日志的最佳实践
- css - CSS 过渡不适用于反应和样式化的组件
- javascript - 如何根据我的需要修复正则表达式?
- python - 如何将 python `dict` 转换为 `sqlalchemy.engine.row`
- visual-studio - 如何更改在 Visual Studio 中显示的起始页
- pandas - 获取前几行的值作为列表
- r - 出于审美目的将(大部分)空白行插入 R 数据框中(导出为 .csv 到 LaTeX)
- c++ - static_assert 表达式不是带有 __builtin_clz 的整数常量表达式
- python - python mysql ValueError:无法处理参数
- class - 是否可以在 SwiftUI 类中显示 UIAlertController?