【问题标题】:Angular 6 Unit testing: I want to stub a declared property for my testAngular 6 单元测试:我想为我的测试存根声明的属性
【发布时间】:2018-05-31 14:29:45
【问题描述】:

我正在使用 Angular 版本 6 和 jasmine。

当我运行 ng test --sourceMap=false

我得到的错误是:videojs 未定义

如果可能,我想存根 videojs。 另外,请注意组件运行良好,只是单元测试失败。

Videojs 是我用来显示视频等的 npm 库。

我正在测试的组件:

import { AfterViewInit, Component } from '@angular/core';

declare const videojs: any;

@Component({
  selector: 'test-details',
  templateUrl: './test-details.component.html'
})
export class TestDetailsComponent implements AfterViewInit {
  public videoJSplayer: any;

  constructor() {}

  ngAfterViewInit(): void {
    this.initVideo();
  }

  public initVideo(): void {
    this.videoJSplayer = videojs(
      document.getElementById('video_player_id'),
      { controls: true, autoplay: false, preload: 'auto' }
    );
  }
}

我的单元测试

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestDetailsComponent } from './test-details.component';

declare const videojs: any;

fdescribe('TestDetailsComponent', () => {
  let component: TestDetailsComponent;
  let fixture: ComponentFixture<TestDetailsComponent>;

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        imports: [],
        declarations: [ TestDetailsComponent ],
        schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
        providers: [
           { provide: videojs, useValue: {} }
        ]
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(TestDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(true).toBeTruthy(true);
  });
});

【问题讨论】:

    标签: angular unit-testing testing jasmine


    【解决方案1】:

    虽然我同意@Ryan 的回答是一种更好的方法,但如果你想模拟一个全局变量,你可以在你的规范中将变量设置在全局范围内。因为它是全局范围,所以您需要在测试运行后小心清理它。

    beforeEach(() => {
      global.videojs = {my: 'mock', object: 'here'};
    });
    
    afterEach(() => {
      delete global.videojs; // Cleanup
    });
    

    旁注:如果更适合您的需要,您可以使用window 而不是global

    【讨论】:

    • 这是一个更好的方法。好答案!
    【解决方案2】:

    您可以注入一个引用 videojs 对象/函数的服务,而不是直接在组件中引用它。然后你可以使用 provide/useClass 在测试中模拟服务,并为 videojs 输入你想要的任何函数/值

    【讨论】:

    • 我已经更新了我的尝试。但仍然没有用 - 你能把我上面的尝试编辑成你的意思吗
    • 你跳过了几个步骤。如果您在 DI 上犯了一个错误,那将是一场艰苦的斗争。我会更详细的说......
    • 我没有视频js的服务。我正在声明 videojs,它来自一个名为 videojs 的 npm 包。 Video js 在组件/浏览器中运行良好,我只需要运行测试即可。
    • 我只是想为单元测试模拟这个声明:declare const videojs: any;
    • @AngularM Okey dokey
    猜你喜欢
    • 2019-03-24
    • 2017-07-26
    • 2020-06-13
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2014-03-31
    • 2019-09-13
    • 1970-01-01
    相关资源
    最近更新 更多