在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
方法。
希望这个解决方法能帮助到你!