首页 文章

Angular单元测试TypeError:无法读取未定义的属性'subscribe'

提问于
浏览
0

我正在使用auth创建入门工具包模板,并使用CRUD创建示例(https://github.com/fransyozef/basic-login-angular

现在我是单元测试的新手,我试图让至少得到运行组件的测试 . 但我陷入困境

TypeError: Cannot read property 'subscribe' of undefined

我认为错误来自于

resolveRoute() {
    this.route.params.subscribe(params => {
      if (params['id']) {
        this.id = +params['id'];
        this.getItem();
      } else {
        this.handleItemNotFound();
      }
     });
  }

在文件https://github.com/fransyozef/basic-login-angular/blob/master/src/app/items/item-edit/item-edit.component.ts

现在我有测试文件:https://github.com/fransyozef/basic-login-angular/blob/master/src/app/items/item-edit/item-edit.component.spec.ts

有人可以帮我一把吗?

1 回答

  • 1

    你应该嘲笑你的路由策略 . 我可以看到你在 TestBed imports 中使用 routingModule . 假设您自己的 routingModule 仅提供您自己的路线,并且无法模拟/侦察其他路线 . 所以我会鼓励你先调整 Test helper routes 里面 test.helper.ts

    export const TestRoutingImports = [
      HttpClientTestingModule,
      RouterTestingModule, // <-- Use RouterTestingModule instead
    ];
    

    (RouterTestingModule)模块设置用于测试的路由器 . 它提供了Location,LocationStrategy和NgModuleFactoryLoader的 Spy 实现 .

    RouterTestingModule provide mocks, RouterModule not.

    你应该做的第二件事是从Testbed中删除你的 provide . 这不是必要的 . 我的意思是以下部分:

    {
      provide: ActivatedRoute, useValue: {
         snapshot: { params: { id: 1 } }
      }
    },
    

    删除它,因为这将是组件提供程序的重写 . 在你的情况下,它是不需要的 .

    我希望我能帮助你 .

相关问题