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:
然后在我需要的文件中声明 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.
解决方法很简单;您只需将 jquery 文件的相同路径包含到项目根文件夹中的 karma.config.js
文件中.该文件位于项目的根目录下.
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屋!