19

我正在为我的 Angular 2 项目使用 Angular-CLI(webpack 版本),并且我还需要使用 jQuery(遗憾的是。在我的情况下,它是 Semantic-UI 的依赖项,我正在使用它来处理菜单下拉菜单)。

我使用它的方式:

npm install jquery --save

然后在数组中列出它angular-cli.json的文件:scripts

scripts": [
  "../node_modules/jquery/dist/jquery.min.js"
]

因此它被包含在捆绑文件中,并且该文件自动用于根 html 文件:

<script type="text/javascript" src="scripts.bundle.js">

然后declare var $: any;在我需要它的文件中,它运行良好。

但是,测试存在问题ng test,因为 Karma 会抛出错误$ is not defined

4

1 回答 1

27

这是因为由 Karma 提供的测试 html 文件没有scripts.bundle.js像通常提供的版本那样包含该文件。

解决方案很简单;您只需将 jquery 文件的相同路径包含到karma.config.js项目根文件夹中的文件中。该文件位于项目的根目录中。

files数组中,添加带有watched标志的路径,如下所示:

files: [
  { pattern: './node_modules/jquery/dist/jquery.min.js', watched: false },    
  { pattern: './src/test.ts', watched: false }
]

Karma 现在应该知道 jQuery 依赖项了。

于 2016-10-13T05:44:11.693 回答