angular - 检查是否在 Angular Jasmine 测试用例中调用内部方法

标签 angular unit-testing jasmine tdd karma-jasmine

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

 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 已被调用”。我应该实现哪些更改才能通过测试用例

最佳答案

应该可以。

例如

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();
  });
});

测试结果: enter image description here

关于angular - 检查是否在 Angular Jasmine 测试用例中调用内部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64929369/

相关文章:

javascript - 改变 Angular 指令添加的 CSS?

Angular Material 以编程方式更改选项卡标签

xcode - 在 Xcode 单元测试中使用 @testable 时为 "No such module"

c# - Entity Framework Core 唯一索引测试

angular - Angular 中的 Mock vs Spy

javascript - Protractor - 比较 2 个数组的差异

node.js - Angular 导航到 Paypal 网址响应

javascript - 诗农.js : How to mock a object constructed with new?

node.js - Jasmine 监视没有父对象导出并在 NODE 中使用 ES6 导入的函数

css - 如何使 Angular2 中的导航栏突出显示?