Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Unit testing: Testing http with real APIs

I am writing unit tests in angular CLI using karma. I want to test http calls with real API and not using mocks. Because API models are changing frequently and I'm looking for a way to be sure about my endpoint responses. Is there any solution or sample code?

Here is on my services that I want to test with real API:

  getCodeRequest(phone: string) {

    let params = new HttpParams();
    params = params.append('phone', String(phone));

    return this.http.get('/auth/request', { params });
  }

I will appreciate any tip or point.

like image 801
ng-hobby Avatar asked May 09 '26 17:05

ng-hobby


1 Answers

What you are describing is not a unit test, and should be avoided in this method of implementation. Instead, you should split it into separate unit tests and e2e tests. Have one unit test for your BE that checks that, given the expected input, it returns the expected output. The second test should check your FE- using mocks - to make sure the request is sent with the right parameters. If you really need to check the passing of the api - you need an e2e test. How exactly this would be implemented depends on your backend environment.

So, to summarize, do not attempt to test the entire API call in a single unit test. Instead,

  1. Make a unit test on the BE for testing behavior on the BE side
  2. Make a unit test in your angular project (using mocks) to test your front end side
  3. If you still need to, make an e2e test for testing end to end things, such as the correct API.

Good luck!

EDIT

Also, as a side note - your API models should not be changing constantly. That is a bad practice that leaves room for things to break. You/your team should sit down and define a clear API that each side sticks to.

Best of luck!

like image 174
PMO1948 Avatar answered May 11 '26 17:05

PMO1948