【发布时间】:2017-07-01 12:46:17
【问题描述】:
我正在为我的项目编写测试用例。但不幸的是,在输入 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 在上传之前就已经开始测试了?
编辑:
我通过在我的index.html 文件中包含<script src='plotly.js'></script> 来导入Plotly。 Plotly 本地存储在与 index.html 相同的文件夹中。
【问题讨论】:
-
您没有在测试中导入 Plotly。你应该有一个类似
import * as Plotly from 'plotly';的行。就像您在使用 Plotly 的 Angular 应用程序的文件中应该有相同的行一样。除非...........您在index.html中包含带有<script>标记的 Plotly 并使用它作为全局变量。但在这种情况下,错误的不仅仅是测试,而是您使用 3rd-party 库的方式。 -
不要对每一个答案都投赞成票,否则其他读者不会知道什么是有用的;点赞好个。
-
@AngularFrance 检查我编辑的问题。那我应该改变导入库的方式吗?
-
@Natalia。这正是我要说的。 :) 您应该使用
import语句导入 3rd 方库。但请注意:根据您使用的模块加载器(SystemJS、webpack...),您可能需要调整配置才能使导入工作。 -
@AngularFrance 我正在使用 webpack。那我应该从 npm 下载
Plotly吗?
标签: javascript unit-testing angular jasmine karma-jasmine