Angular 2 和 jQuery - 如何测试?
Angular 2 and jQuery - how to test?
我正在为我的 Angular 2 项目使用 Angular-CLI(webpack 版本),我还需要使用 jQuery(遗憾的是。在我的例子中,它依赖于语义-UI,我用它来处理菜单下拉菜单)。
我的使用方式:
npm install jquery --save
然后在 scripts
数组中的 angular-cli.json
文件中列出:
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
。
这是因为测试 html 文件,由 Karma 提供,不包含正常服务版本所包含的 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 依赖关系。
我正在为我的 Angular 2 项目使用 Angular-CLI(webpack 版本),我还需要使用 jQuery(遗憾的是。在我的例子中,它依赖于语义-UI,我用它来处理菜单下拉菜单)。
我的使用方式:
npm install jquery --save
然后在 scripts
数组中的 angular-cli.json
文件中列出:
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
。
这是因为测试 html 文件,由 Karma 提供,不包含正常服务版本所包含的 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 依赖关系。