4

I have a component with an image in template

 <div class="logo"><img src="../images/logo.png"/></div>

When running karma task it throws such error

Uncaught Error: Cannot find module "../images/logo.png"

To mention that app renders the image fine , only karma is complaining.

Any advice will be appreciated.

rjomir
  • 252
  • 3
  • 11

3 Answers3

17

You could try something like this:

it('should render the logo', async(() => {
  const fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  const compiled = fixture.debugElement.nativeElement;
  expect(compiled.querySelector('div.logo>img').src).toContain('/images/logo.png');
}));
Leo
  • 7,914
  • 2
  • 35
  • 46
  • 2
    This should be the accepted answer. Just tried it myself and it works. – blueprintchris May 03 '18 at 08:25
  • 2
    This verifies that the image element exists and the source points to a specific URL string. But How to check that '/images/logo.png' actually exists? – Ya. Sep 27 '18 at 19:21
1

Let's assume you are using karma-jasmine to run the test. The files will be hosted on port 9876.

Let's say your img src is ./assets/images/logo.png, then you should expect the src to be http://localhost:9876/assets/images/logo.png instead of just ./assets/images/logo.png

J Shi
  • 53
  • 2
  • 7
0

You can also use proxies and files property in karma.conf.js to serve files and proxy it.

Add files to be served in files property

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

Also to proxy these files with different url/ path, update proxies property

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

Now, when you try to access http://localhost:9876/assets/logo.png it will be a proxy call to src/assets/logo.png (all src assets are accessible like this as well http://localhost:9876/base/src/assets/logo.png )

Niraj Tathe
  • 171
  • 1
  • 7