【问题标题】:Mock Activated Route With Params in Angular使用 Angular 中的参数模拟激活的路由
【发布时间】:2020-06-15 16:19:40
【问题描述】:

问题

如何在我的单元测试中模拟ActivatedRoutes

服务:

  constructor(
    private route: ActivatedRoute,
    private knowledgeModelService: KnowledgeModelService
  ) {
    route.params.pipe(map(p => p.modelId)).subscribe((modelId) => {
      this.modelId = modelId;
    });
  }

我的单元测试:

模拟类

  class ActivatedRouteMock {
    // params = of([{modelId: 'test1'}]);
    params = { paramMap: of( convertToParamMap( { modelId: 'test1' } ) ) }
  }

...

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ StatsComponent ],
      providers: [
        {
          provide: ActivatedRoute, useClass: ActivatedRouteMock
        },

我尝试了差异。方法来自:

Angular2 RC5 Mock Activated Route Params

Angular2 how to Mock Activated Route Params subscribed

Unit test angular activate route correctly

Angular 4 - Failed: Can't resolve all parameters for ActivatedRoute: (?, ?, ?, ?, ?, ?, ?, ?)

但我没有得到任何地方。

错误:

route.params.pipe is not a function

【问题讨论】:

    标签: angular unit-testing angular-activatedroute


    【解决方案1】:

    你试过这样吗?

    class ActivatedRouteMock {
        params = of( { modelId: 'test1' } )
    }
    

    【讨论】:

    • 抱歉,我试过了,但是里面有第二个 Observable 被错误地模拟了,所以我认为它仍然是第一个。我的错。
    猜你喜欢
    • 2017-01-15
    • 1970-01-01
    • 2020-08-12
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多