【问题标题】:Angular Unit Test Video Resolution角度单元测试视频分辨率
【发布时间】:2019-03-29 11:09:44
【问题描述】:

我正在检查视频文件的视频分辨率。代码运行良好,现在我正忙于对这个函数进行单元测试。

我尝试监视 videoWidth 和 videoHeight 属性,但没有成功。相反,我收到错误消息说这些属性不存在。我发现的问题是 HTMLVideoElement 的 videoWidth 和 videoHeight 属性是只读的。我该如何测试它?

TS

videoResolutionTest(evt: KeyboardEvent) {
        const currentVideo = evt.target as HTMLVideoElement;

        if ((currentVideo.videoWidth <= 720) && (currentVideo.videoHeight <=500 540)) {
            this.displayError('resolutionError', 2000);
        }
    }

HTML

<video (loadedmetadata)="videoResolutionTest($event)">
<source type="video/mp4">
</video>

【问题讨论】:

标签: angular typescript unit-testing dom jasmine


【解决方案1】:

您可以创建一个模拟事件对象并转换它的类型。模拟事件包含具有不同分辨率的目标。

使用 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();
  });
});

单元测试结果:

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 1970-01-01
    • 2016-06-01
    • 2021-03-29
    • 2022-01-27
    • 2018-01-18
    • 2016-01-10
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多