您可以创建一个模拟事件对象并转换它的类型。模拟事件包含具有不同分辨率的目标。
使用 Angular v11+ 的单元测试解决方案:
example.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-video',
template: `
<video (loadedmetadata)="videoResolutionTest($event)">
<source type="video/mp4" />
</video>
`,
})
export class VideoComponent {
videoResolutionTest(evt: KeyboardEvent) {
const currentVideo = evt.target as HTMLVideoElement;
if (currentVideo.videoWidth <= 720 && currentVideo.videoHeight <= 540) {
this.displayError('resolutionError', 2000);
}
}
displayError(arg0: string, arg1: number) {
throw new Error('Method not implemented.');
}
}
example.component.spec.ts:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { VideoComponent } from './example.component';
fdescribe('55416150', () => {
let fixture: ComponentFixture<VideoComponent>;
let component: VideoComponent;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [VideoComponent],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(VideoComponent);
component = fixture.componentInstance;
});
})
);
it('should display error', () => {
const evt = {
target: {
videoWidth: 400,
videoHeight: 300,
},
};
const displayErrorStub = spyOn(component, 'displayError').and.stub();
component.videoResolutionTest((evt as unknown) as KeyboardEvent);
expect(displayErrorStub).toHaveBeenCalledWith('resolutionError', 2000);
});
it('should do nothing', () => {
const evt = {
target: {
videoWidth: 1024,
videoHeight: 768,
},
};
const displayErrorStub = spyOn(component, 'displayError').and.stub();
component.videoResolutionTest((evt as unknown) as KeyboardEvent);
expect(displayErrorStub).not.toHaveBeenCalled();
});
});
单元测试结果: