javascript - Angular 单元测试类型错误: Cannot read property 'subscribe' of undefined

标签 javascript angular unit-testing frontend karma-jasmine

我正在使用身份验证创建入门工具包模板以及使用 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

有人可以帮我解决这个问题吗?

最佳答案

您应该模拟您的路由策略。正如我所看到的,您在 TestBed 导入 中使用了 routingModule 。假设您的自己的 routingModule 仅提供您自己的路由,并且无法模拟/监视其他路由。因此,我鼓励您首先调整 test.helper.ts 内的 Test helper paths

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

The(RouterTestingModule) modules sets up the router to be used for testing. It provides spy implementations of Location, LocationStrategy, and NgModuleFactoryLoader.

RouterTestingModule 提供模拟,RouterModule 不提供。

您应该做的第二件事是从测试台中删除您的provide。这里就没有必要了。我的意思是以下部分:

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

删除它,因为这将覆盖组件提供者。在你的情况下,不需要。

希望能帮到你。

关于javascript - Angular 单元测试类型错误: Cannot read property 'subscribe' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53702866/

相关文章:

javascript - 如何使用react和firebase向所有用户显示实时数据?

javascript - 使用 html 悬停代码选项打印/隐藏数据

angular - angular4应用程序中的FormData上传

javascript - 传递类引用的 Angular 范围问题中的 Highcharts

unit-testing - 在 spock 中运行测试时出现 MissingPropertyException

javascript - Typescript - TypeError myclass.myFunction 不是函数

javascript - 在 vtiger 7 中使用 javascript/jQuery 设置选项列表值?

html - 声明忽略 parent 填充的背景

java - JUnit 测试中的假设与断言

python - 如何在单元测试中重用单元测试方法而不实际测试它