【问题标题】:Getting Error Cannot read property 'extras' of null when i'm running karma test运行业力测试时出现错误无法读取 null 的属性“附加”
【发布时间】:2019-10-07 09:51:43
【问题描述】:

我制作了一个组件,并使用以下代码从路线中获取一些数据。当我尝试 ng test 时出现错误:

TypeError:无法读取 null 的属性“附加”

我应该在这个组件的规范文件中导入什么来读取“状态”?在我的规范文件中,我添加了import { RouterTestingModule } from '@angular/router/testing',但仍然不起作用;

const navigation = this.router.getCurrentNavigation();
        const state = navigation.extras.state;
        console.log(state);

【问题讨论】:

  • 看起来this.router.getCurrentNavigation(); 没有获得任何值。请检查并更新您的问题

标签: angular karma-runner


【解决方案1】:
@Component({
  selector: 'app-root',
  template: `<pre>{{ state$ | async | json }}</pre>`,
})
export class AppComponent implements OnInit {
  private state$: Observable<object>;

  constructor(public router: Router) { }

  ngOnInit() {
    this.state$ =  this.router.events.pipe(
      filter(e => e instanceof NavigationStart),
      map(() => this.router.getCurrentNavigation().extras.state)
    )
  }
}

欲了解更多信息:Passing Data between Routes in Angular

【讨论】:

    【解决方案2】:

    就我而言,我通过添加

    修复了所有这些错误
    afterEach(() => {
        TestBed.resetTestingModule();
    });
    

    在我所有的 *.spec.ts 文件中。

    我的文件如下所示:

    beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
    
    it('should create', () => {
        expect(component).toBeTruthy();
    });
    
    afterEach(() => {
        TestBed.resetTestingModule();
    });
    

    【讨论】:

      【解决方案3】:

      你需要检查 if 语句。

      data: '';
      constructor(public router: Router) {
      let data = this.router.getCurrentNavigation().extras.state;
         if(data)
           this.data = data;
       }
      

      重要* 上面的代码需要在您的 constructor() 中,因为这将始终确保您可以访问数据。

      【讨论】:

        猜你喜欢
        • 2020-06-02
        • 2020-09-05
        • 2021-04-07
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 2018-06-28
        • 2018-04-14
        • 2018-07-01
        相关资源
        最近更新 更多