要在HostListener函数的条件Else部分运行单元测试,我们可以使用TestBed和ComponentFixture。首先,创建一个测试宿主组件,并在其中定义一个mock函数来测试条件Else部分。然后,使用TestBed创建组件实例,并使用ComponentFixture.detectChanges()触发变更检测周期。最后,使用spyOn()方法监听mock函数的调用。以下是示例代码:
组件:
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'my-cmp',
template: `Component`
})
export class MyComponent {
@HostListener('window:resize', ['$event'])
onResize(event) {
if (event.target.innerWidth > 768) {
console.log('Larger than 768px');
} else {
this.onSmallerScreen();
}
}
onSmallerScreen() {
console.log('Smaller than 768px');
}
}
测试:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
let onSmallerScreenSpy: jasmine.Spy;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MyComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
onSmallerScreenSpy = spyOn(component, 'onSmallerScreen');
fixture.detectChanges();
});
it('should call onSmallerScreen when window width is smaller than 768px', () => {
const event = new Event('resize');
Object.defineProperty(event.target, 'innerWidth', { writable: true, configurable: true, value: 500 });
window.dispatchEvent(event);
expect(onSmallerScreenSpy).toHaveBeenCalled();
});
it('should call console.log when window width is larger than 768px', () => {
const event = new Event('resize');
Object.defineProperty(event.target, 'innerWidth', { writable: true, configurable: true, value: 800 });
window.dispatchEvent(event);