Angular 2 and jQuery - how to test?

走远了吗. 提交于 2019-12-05 12:03:34

问题


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

The way I am using it:

npm install jquery --save

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

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:

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

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

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


回答1:


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

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.

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 now should know about the jQuery dependency.



来源:https://stackoverflow.com/questions/40013155/angular-2-and-jquery-how-to-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!