在Angular 9中,你可以使用Karma和spyOn方法来模拟多态性的window.scroll事件。下面是一个示例解决方法:
spyOn方法和window对象:import { ComponentFixture, TestBed } from '@angular/core/testing';
describe('YourComponent', () => {
let component: YourComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [YourComponent]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should handle window scroll event', () => {
spyOn(window, 'scroll');
// 在这里编写触发scroll事件的代码
expect(window.scroll).toHaveBeenCalled();
});
});
it块中,使用spyOn方法来模拟window.scroll事件。然后,你可以编写触发该事件的代码,并使用expect语句来验证是否已触发该事件。请注意,你需要确保在beforeEach方法中创建组件实例之前调用spyOn方法。
希望这个解决方法能帮助到你!