Angular 2和jQuery - 如何测试?

[英]Angular 2 and jQuery - how to test?


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).

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

The way I am using it:

我使用它的方式:

npm install jquery --save

Then listing in it angular-cli.json file in the scripts array:

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

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

So it gets included into bundle file and this file is automatically used to root html file:

所以它被包含到bundle文件中,这个文件自动用于root html文件:

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

Then declare var $: any; in files where I need it and it works well.

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

However there is a problem with ng test tests, as Karma throws an error $ is not defined.

然而,ng测试测试存在问题,因为Karma抛出错误$未定义。

1 个解决方案

#1


22  

This is because the testing html file, provided by Karma, doesn't include the scripts.bundle.js file as normally served version does.

这是因为Karma提供的测试html文件不包含正常服务版本的scripts.bundle.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.

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

In files array, add the path with watched flag like this:

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

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

Karma now should know about the jQuery dependency.

Karma现在应该知道jQuery依赖。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/10/13/f3db9d17f9011fb5706b047848be22ff.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com