我正在学习使用 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();
});
});
关于angular - 检查是否在 Angular Jasmine 测试用例中调用内部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64929369/