【问题标题】:could not find an object to spy upon for navigateBackToLanding找不到可监视的对象以进行 navigateBackToLanding
【发布时间】:2018-12-28 23:40:17
【问题描述】:

在运行测试时,我收到此错误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']);
  }

组件规格.ts

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>

【问题讨论】:

    标签: angular jasmine karma-jasmine


    【解决方案1】:

    嗯,这很简单:你永远不会在任何地方初始化变量component。因此,正如错误消息所说,没有对象可以监视,因为 component 是未定义的。

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

    【讨论】:

    • 谢谢,现在我收到了这个错误Failed: Cannot read property 'click' of null
    • 这可能意味着DOM中没有按钮,可能是因为你没有调用fixture.detectChanges()。
    • button 标记是使用服务创建的,默认情况下在 html 文件中不可用。我在我的问题中添加了生成的 html 代码
    • 我也试过query(By.css('.bwc-subheader__button-back'))还是没有运气
    • 您不能使用 Angular 以这种方式动态生成代码(除非您发布编译器并即时编译模板,这正是 AOT 编译要避免的)。改变你的设计。 HTML 应该由组件模板生成,而不是由服务生成。无论如何,我不能在没有看到任何代码的情况下进行远程调试。我回答了你最初的问题,现在花点时间研究下一个问题。
    猜你喜欢
    • 2017-11-30
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    相关资源
    最近更新 更多