当组件模板有一个带有routerLink属性的标签时,如何在Angular Testbed中创建组件?

时间:2018-02-13 11:28:32

标签: angular

我正在以这种方式编译组件:

TestBed.configureTestingModule({
  imports: [ReactiveFormsModule, MaterialModules, RouterTestingModule, BrowserAnimationsModule],
  declarations: [SigninComponent, LoaderComponent],
  providers: [
    MatSnackBar, {
      provide: Router, useClass: RouterStub
    }, {
      provide: ActivatedRoute, useValue: {
        snapshot: { params: Observable.of({ email: 'test@email.in' }) }
      }
    }, {
      provide: NgZone, useClass: MockNgZone
    },
    LoaderService,
    FormBuilder,
    StoreOperationService
  ]
})
await TestBed.compileComponents()

模板具有以下标记:

     <a [routerLink]="[forgotPasswordUrl]">Forgot password?</a>

我收到以下错误:

    TypeError: Cannot read property 'subscribe' of undefined
    at new RouterLinkWithHref (webpack:///node_modules/@angular/router/@angular/router.es5.js:5028:0 <- config/spec-bundle.js:41957:42)

这是RouterStub:

    class RouterStub {
        navigateByUrl(url: string) { return url; }
    }

如何摆脱错误?

2 个答案:

答案 0 :(得分:1)

感谢@ estus的评论,我指出了正确的方向。这个link为各种路由指令提供了存根。

我创建了一个存根文件:

import { Directive, Input } from '@angular/core'
@Directive({
  selector: '[routerLink]',
  host: {
    '(click)': 'onClick()'
 }
})
export class RouterLinkStubDirective {
  @Input('routerLink') linkParams: any
  navigatedTo: any = null

  onClick() {
    this.navigatedTo = this.linkParams
  }
}

新的TestBed配置如下所示:

class RouterStub {
    navigateByUrl(url: string) { return url; }
}

TestBed.configureTestingModule({
  imports: [ReactiveFormsModule, MaterialModules, BrowserAnimationsModule],
  declarations: [SigninComponent, LoaderComponent, RouterLinkStubDirective],
  providers: [
    MatSnackBar, {
      provide: Router, useClass: RouterStub
    }, {
      provide: ActivatedRoute, useValue: {
        snapshot: { params: Observable.of({ email: 'test@email.in' }) }
      }
    }, {
      provide: NgZone, useClass: MockNgZone
    },
    LoaderService,
    FormBuilder,
    StoreOperationService
  ]
})
await TestBed.compileComponents()

我删除了RouterTestingModule导入,并将RouterLinkStubDirective添加到声明中。

答案 1 :(得分:0)

只需使用路由器测试模块。

import { RouterTestingModule } from '@angular/router/testing';

并将其添加到测试台的模块中:

  beforeEach(() => {
    TestBed.configureTestModule({
      imports: [
        RouterTestingModule.withRoutes([
          {path: '/forgot', component: ForgotPasswordCmp}
        ])
      ]
    });
  });