找不到要监视的对象作为navigationBackToLanding

时间:2018-12-28 15:18:24

标签: angular jasmine karma-jasmine

运行测试时,出现此错误could not find an object to spy upon for navigateBackToLanding

我已经搜索并完成了提到的所有步骤,但仍然出现错误

 could not find an object to spy upon for navigateBackToLanding

不确定我在这里缺少什么。

component.ts

  ngOnInit () {
    this.bwcPageTemplateCommunicatorService.subheader.next({
      title: this.title,
      backAction: {
        label: 'back',
        callback: () => this.navigateBackToLanding()
      }
    });
  }

  public navigateBackToLanding () {
    this.router.navigate(['portal']);
  }

组件规格

describe('CpDetailPageComponent', () => {
  let component: CpDetailPageComponent;
  let fixture: ComponentFixture<CpDetailPageComponent>;
  let onClickMock;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      imports: [RouterTestingModule],
      declarations: [CpDetailPageComponent],
      providers: [
        BwcPageTemplateCommunicatorService,
        BwcTocService,
        BwcScrollSpyService,
        BwcScrollService
      ]
    });
    TestBed.compileComponents();
    fixture = TestBed.createComponent(CpDetailPageComponent);
    onClickMock = spyOn(component, 'navigateBackToLanding').and.callThrough();
  }));

  it('should call navigateBackToLanding method', () => {
    fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
    expect(onClickMock).toHaveBeenCalled();
  });

});

HTML

<button class="bwc-subheader__button-back ng-star-inserted" mat-icon-button="" type="button" aria-label="back"></button>

1 个答案:

答案 0 :(得分:0)

嗯,这很简单:您永远不会在任何地方初始化变量component。由于错误消息component未定义,因此没有任何对象可以监视,就像错误消息所指出的那样。

component = fixture.componentInstance;
onClickMock = spyOn(component, 'navigateBackToLanding').and.callThrough();