rjomir
rjomir

Reputation: 304

Angular2 Jasmine Test Image Source

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.

Upvotes: 6

Views: 10244

Answers (3)

Niraj Tathe
Niraj Tathe

Reputation: 191

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 )

Upvotes: 0

Leo
Leo

Reputation: 10833

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');
}));

Upvotes: 21

J Shi
J Shi

Reputation: 53

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

Upvotes: 1

Related Questions