Angular 2和jQuery-如何进行测试? [英] Angular 2 and jQuery - how to test?
问题描述
我在Angular 2项目中使用的是Angular-CLI(Webpack版本),我还需要使用jQuery(不幸的是.在我的情况下,它是Semantic-UI的依赖项,我正在使用它来处理菜单下拉菜单).
I am using Angular-CLI (webpack version) for my Angular 2 project and I also need to use jQuery (sadly. In my case, it's a dependency of Semantic-UI and I am using it for handling menu dropdowns).
我的使用方式:
npm install jquery --save
然后在scripts
数组中的angular-cli.json
文件中列出该文件:
Then listing in it angular-cli.json
file in the scripts
array:
scripts": [
"../node_modules/jquery/dist/jquery.min.js"
]
因此它被包含在捆绑文件中,并且该文件自动用于根html文件:
So it gets included into bundle file and this file is automatically used to root html file:
<script type="text/javascript" src="scripts.bundle.js">
然后在需要的文件中添加declare var $: any;
,效果很好.
Then declare var $: any;
in files where I need it and it works well.
但是ng test
测试存在问题,因为Karma抛出错误$ is not defined
.
However there is a problem with ng test
tests, as Karma throws an error $ is not defined
.
推荐答案
这是因为Karma提供的测试html文件不包含scripts.bundle.js
文件,这与通常提供的版本不一样.
This is because the testing html file, provided by Karma, doesn't include the scripts.bundle.js
file as normally served version does.
解决方案很简单;您只需在项目的根文件夹中的karma.config.js
文件中包含jquery文件的相同路径.该文件位于项目的根目录.
The solution is easy; you just include same path to the jquery file into karma.config.js
file in project's root folder. This file is available at the root of the project.
在files
数组中,添加带有watched
标志的路径,如下所示:
In files
array, add the path with watched
flag like this:
files: [
{ pattern: './node_modules/jquery/dist/jquery.min.js', watched: false },
{ pattern: './src/test.ts', watched: false }
]
Karma现在应该了解jQuery依赖项.
Karma now should know about the jQuery dependency.
这篇关于Angular 2和jQuery-如何进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!