How to fix 404 errors for webserver during karma unit testing Angular

Learn to fix web server 404 not found errors in testing angular components or directives.

This post includes a solution for 404 errors for loading assets files such as JSON and images during running karma runner in Angular.

Here is a sample error

2021 01:06:33.123:WARN [web-server]: 404: /assets/arrow.png
2021 01:06:33.123:WARN [web-server]: 404: /assets/down.png

Suppose, UI component contains png or any image file to display images. An error thrown while running unit testing a component

Generally, When the ng test command runs, It starts a web server and executes unit test files and test them. Also, ng serve command also starts web server, but, Running ng test uses separate karma runtime environments.

Testing Component throws an error during asset loading in testing components.

For example, Angular component contains image tag.

app.component.ts:

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

Test cases for this angular component as follows.

it("should render image", () => {
  const fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  const compiled = fixture.nativeElement;
  expect(compiled.querySelector("img")).toBeDefined();
});

Throws an error something like this

WARN [web-server]: 404: /assets/images/logo.png

The error tells that image does not found during unit test execution with karma and angular unit testing.

What does karma do, while running the ng test command?

  • Karma compiles all spec test files
  • Create a request HTML page that contains all static files JavaScript images and JSON.
  • Starts web server to serve a request from unit testing code
  • Web server loads all component code as well as static assets
  • Static should be available to load properly-

There are multiple ways to fix 404 errors in image loading.

First Way:

Create images files required for components locally, it is not recommended copying or create an image and these used for testing only

Second way, is to configure the karma.config.js file

  • add files and array with assets pattern in the karma configuration file - karma.config.
 files: [
    { pattern: 'assets/images/*.*', watched: true, included: true, served: true },
],

files section of these configurations contains pattern watched included and served values

  • add proxies for the asset folder
proxies: {
    "/assets/": "/app/assets/"
}

in proxies attribute, The first value points to the original request that is coming the second value is a karma runner that serves the files for assets

We are running the test from the src folder, we have to provide path stars from the app folder for karma runner.

Whenever a request contains an assets’ path, it serves the files from the app/assets/ folder.

Conclusion

You learned how to fix karma web server 404 errors in Angular unit testing for static files like images, json files.