Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse proxy configuration for Karma during Angular testing

My application makes calls to a backend web service. During development I configure reverse proxy for the Angular CLI server and everything works fine.

ng serve --proxy-config proxy.config.json

I need to do the same for Karma during unit testing. I add this to karma.conf.js.

proxies: {
  "/books":"http://localhost:3000/",
  "/books/*":"http://localhost:3000/",
}

None of this works. My calls always get 404. If, however, I configure a full URL, it works.

proxies: {
  "/books/167":"http://localhost:3000/books/167"
}

How can I properly configure reverse proxy using wildcard?

like image 610
RajV Avatar asked Feb 20 '18 17:02

RajV


People also ask

What is karma config in angular?

Karma is the foundation of our testing workflow. It brings together our other testing tools to define the framework we want to use, the environment to test under, the specific actions we want to perform, etc. In order to do this Karma relies on a configuration file named by default karma. conf.

What is the use of proxy config in angular?

Use the proxying support in the webpack development server to divert certain URLs to a backend server, by passing a file to the --proxy-config build option. For example, to divert all calls for http://localhost:4200/api to a server running on http://localhost:3000/api , take the following steps.

What is karma JSON in angular?

Karma is a tool which spawns a web server that executes tests defined by using supported test frameworks for each connected browser. Karma can be used to do testing using most of the common frameworks (including Jasmine, Mocha, QUnit).


1 Answers

You should not use backend in the unit test. As the name shows it is about testing in units. The dependencies of the unit you test (e.g. service or component) should be mocked. This way real http service won't be called, only a mock (e.g. Observable) with the same functionality, so only the unit will be tested and the test won't fail because of the dependency.

The proxy is only needed in the e2e test as it tests the application as a whole. The e2e tests inherit the --proxy-config option from the serve script.

Examples:

  • MockBackend for test
  • Testing guide
like image 57
androbin Avatar answered Oct 20 '22 17:10

androbin