如何将外部库包含在单元测试中:: Angular2-CLI

时间:2017-02-13 13:49:44

标签: javascript unit-testing angular jasmine karma-jasmine

我正在为我的项目编写测试用例。但不幸的是,在通过键入ng test开始测试后,我收到以下错误:

Error: Error in :0:0 caused by: Plotly is
ReferenceError: Plotly is not defined

Plotly是一个外部图表库。我试图在test文件中声明它:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MaterialModule } from '@angular/material';
import { WatchlistComponent } from './watchlist.component';
declare let Plotly: any;

describe('SystemComponent', () => {
  let component: WatchlistComponent;
  let fixture: ComponentFixture<WatchlistComponent>;
  let element;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ WatchlistComponent ],
      imports: [ FormsModule, MaterialModule ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(WatchlistComponent);
    component = fixture.componentInstance;
    element = fixture.nativeElement;
    fixture.detectChanges();
  });


  it('should return a positive number', () => {
    expect(component.getScreenHeight()).toMatch(/\d+/);
  });

});

不幸的是,它仍然没有看到Plotly并返回错误。 getScreenHeight()函数的第一个测试用例甚至没有启动。

也许jasmine甚至在上传之前就开始了测试?

修改: 我通过在Plotly文件中加入<script src='plotly.js'></script>来导入index.htmlPlotly本地存储在与index.html相同的文件夹中。

1 个答案:

答案 0 :(得分:4)

通过在karma.config.js中添加文件配置,将 plotly.js with path )文件加载到Karma测试环境中,如下所示:

karma.config.js

config.set({
   ..
   files: ['plotly.js']
   ..
});