Angular 2 and jQuery - how to test?
Asked Answered
S

1

20

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.

Simplify answered 13/10, 2016 at 5:44 Comment(1)
How did you include jQuery in your component spec? I'm getting the same error and tried to include jQuery via the files array in karma.conf.js.Ralphralston
S
28

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.

Simplify answered 13/10, 2016 at 5:44 Comment(2)
Oh gosh, that was one step away from what i was trying to do for 2 days, I just removed "included" flag from the same line, and it worked!Colangelo
when i use this code jQuery('#confirmDialogModal').modal('hide');, I get modal is not a function error while running test cases, but in real application it works. also jQuery('#facilityIdModalButton').click(); doesnt throw any throw while running test cases. any idea how to fix or skip jquery callsBenedetta

© 2022 - 2024 — McMap. All rights reserved.