如何模拟角度ActivatedRoute

问题描述 投票:0回答:2

我有ActivatedRoute的代码与map,然后是subscribe

export class MyComponent implements OnInit {

    constructor(private actr: ActivatedRoute) {

    this.actr.data.map(data => data.aList).subscribe((res) => {
        console.log('res ------------------------- ', res); // It is not showing this.
        this.myResponse = res;
    });
}

   ngOnInit() {
      // some code
      // myResponse is undefined
   }

}

我在spec文件中尝试过:

class MockActivatedRouter {

    public map = (data) => data.aList = of({some: [] });
    // Or 
    public map = (data) => of({some: [] });
 }

它们都不起作用。

angular unit-testing mocking rxjs router
2个回答
1
投票

我想你想这样嘲笑它:

class MockActivatedRouter {
  data = of({some: [] }); // Dont remember the old rxjs5 syntax but you might want to use Observable.of(...)
}

意味着ActivatedRoute有一个属性data,它是你在构造函数中订阅的可观察对象。

我通常只使用普通对象来模拟它,并提供可观察的Subject,以便能够在测试中随时发出。

我想你知道如何在测试中提供你的模拟:

TestBed.configureTestingModule({
  ...
  providers: [{
    provide: ActivatedRoute,
    useClass: MockActivatedRouter
  }]
});

0
投票

事实证明我们可以简单地做到:

class MockActivatedRouter {
  public map = (data) => of(MyResponse.data.aList);
}

class MyResponse {
  static data = {
     // data 
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.