如何在 Angular 9 组件单元测试中调用假函数
How to call a fake function in Angular 9 component unit test
我有一个包含两个方法的 angular 组件
class MyComponent {
constructor() {
...
}
loadDataSource() {
...
}
runFilter() {
//some other logic here
this.loadDataSource();
}
}
我有一个单元测试
describe('running filters', () => {
beforeEach(() => {
component.runFilter();
const spy = jasmine.createSpyObj(['loadDataSource']);
spy.loadDataSource.and.callFake(function() { });
});
it('should call load data source', () => {
expect(component.loadDataSource).toHaveBeenCalled();
});
});
但是,这似乎仍然在调用 runFilter 时调用 loadDataSource 的实际实现,而不是我提供的空假函数。
如何在调用 runFilter 时测试调用了 loadDataSource 方法,而不实际调用实际实现?这样做的原因是我不想调用 loadDataSource 的任何逻辑。
试试这个
describe('running filters', () => {
beforeEach(() => {
spyOn(component, 'loadDataSource').and.callFake();
});
it('should call load data source', () => {
component.runFilter();
expect(component.loadDataSource).toHaveBeenCalled();
});
});
我有一个包含两个方法的 angular 组件
class MyComponent {
constructor() {
...
}
loadDataSource() {
...
}
runFilter() {
//some other logic here
this.loadDataSource();
}
}
我有一个单元测试
describe('running filters', () => {
beforeEach(() => {
component.runFilter();
const spy = jasmine.createSpyObj(['loadDataSource']);
spy.loadDataSource.and.callFake(function() { });
});
it('should call load data source', () => {
expect(component.loadDataSource).toHaveBeenCalled();
});
});
但是,这似乎仍然在调用 runFilter 时调用 loadDataSource 的实际实现,而不是我提供的空假函数。
如何在调用 runFilter 时测试调用了 loadDataSource 方法,而不实际调用实际实现?这样做的原因是我不想调用 loadDataSource 的任何逻辑。
试试这个
describe('running filters', () => {
beforeEach(() => {
spyOn(component, 'loadDataSource').and.callFake();
});
it('should call load data source', () => {
component.runFilter();
expect(component.loadDataSource).toHaveBeenCalled();
});
});