18

When I try and run an ng test, all of my modules and components load correctly, but any of the assets I include in <img> tags do not render because they're not being served in the /assets folder (like they would in a build or during development using ng serve)

In addition to this, it would be nice to know how to get the global styles.scss/css file to be included in the test, as I can only get these styles to render if I drop the CSS into a component and disable ViewEncapsulation.

I'm on the latest angular-cli webpack release (Beta 15)

Any help is greatly appreciated.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150

1 Answers1

42

I found the answer!

By default, the karma setup in the angular-cli (webpack) doesn't serve your assets folder by default, but this is very simple to add (once you sift through the documentation)

below is a screenshot of my results and the code I added to get it to work

enter image description here

To the left you can see my image of Billy Mays is now being served, to the right if you look at the 'file' section of the json, I added the following:

{ pattern: './src/assets/**', watched: false, included:false, nocache:false, served:true }

I also added a proxies property, to take the served content (served by default at http://localhost:[karma port number]/base

proxies: {
   '/assets/': '/base/src/assets/'
},

By specifying /assets/ as the folder proxy, karma uses the path localhost:[karma port number]/assets instead of the default.

I'm happy I was able to my own question, and hope this helps some people starting with the angular-cli!

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • 3
    I know it says to not say thanks, but, thank you! I missed the 'files' section above on first read because it is not marked as code like the 'proxies' section - perhaps you could reformat? – dylan oliver Dec 21 '16 at 20:06
  • It work as solution for this bug. https://github.com/angular/angular-cli/issues/14593 – Denis Anisimov Jul 08 '19 at 13:54
  • @ProgrammerInProgress, Do you know how to request a file via http: http.expectOne('./assets/i18n/2/en.json') will this work? – Juliyanage Silva Feb 07 '20 at 14:18
  • 1
    Very old but very relevant post. Thank you indeed. Btw karma and webpack currently crashes when the proxies part is not set with `UnhandledRejection: Cannot read property 'range' of undefined`. See my post https://stackoverflow.com/a/65347089/2416394 which will ultimately link to you, because you solution is much better :) – Samuel Dec 22 '20 at 08:15