首页 > 解决方案 > 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();
  }

标签: angulartypescriptkarma-jasmine

解决方案


您的错误来自这里:

this.router.routerState.root.firstChild.routeConfig.data

您确实已经导入了路由器测试模块,但不要期望它会根据您的特定需求进行设置。

为避免这种情况,您可以在beforeEach函数中添加自定义配置:

RouterTestingModule.withRoutes([] as Route[], {} as ExtraOptions);

只需将参数替换为适合您的测试用例的值。


推荐阅读