【问题标题】:check if inner method is being called in angular jasmine test case检查是否在 angular jasmine 测试用例中调用了内部方法
【发布时间】:2020-11-20 12:19:30
【问题描述】:

我正在学习使用 jasmine 为我的 Angular 应用程序编写测试用例,但在一个特定的场景中,我有一个调用其他私有函数/方法的组件内部的函数,该函数如下所示

 public rPage() {
    this.setData(); // private method 
    this.setPage(); // private method
  }

我写了测试用例来测试它如下

 it('should call setData from RPage', () => {
    //@ts-ignore
    const spy = spyOn(component, 'setData');
    component.rPage();
    fixture.detectChanges();
    expect(spy).toHaveBeenCalled();
  });

但是当我运行 ng test 时,测试用例失败并显示“预期的 spy setData 已被调用。我应该进行哪些更改才能通过测试用例

【问题讨论】:

  • 你打电话给rPage了吗?
  • @BojanKogoj 是的
  • 我曾经以expect(component.setData).toHaveBeenCalled() 进行测试,但我怀疑这是一个问题。

标签: angular unit-testing jasmine tdd karma-jasmine


【解决方案1】:

它应该可以工作。

例如

example.component.ts:

import { Component } from '@angular/core';

@Component({})
export class ExampleComponent {
  public rPage() {
    this.setData();
    this.setPage();
  }
  private setData() {}
  private setPage() {}
}

example.component.spec.ts:

import { ExampleComponent } from './example.component';

fdescribe('64929369', () => {
  it('should call setData from RPage', () => {
    const component = new ExampleComponent();
    //@ts-ignore
    const setDataSpy = spyOn(component, 'setData');
    //@ts-ignore
    const setPageSpy = spyOn(component, 'setPage');
    component.rPage();
    expect(setDataSpy).toHaveBeenCalled();
    expect(setPageSpy).toHaveBeenCalled();
  });
});

测试结果:

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多