Friday, December 20, 2019

How do I test a service in an Angular application?

What a puzzle! I have found an article online that just shows off testing services that are the equivalent of static utilities in C#, but where is the fun in that? The really question here is: How do I test a service that has external dependencies (API calls) in it? I think you are going to have to do the deps trick to hand in external dependencies to a service, stub/mock the deps, and then unit test the rest of functionality in the service. This would mean that HttpClient calls are kept in a few common methods and that services just prep what is handed into those methods, etc. This may sound clunky, but it is less clunky if you are doing GraphQL instead of ReST wherein you are always using the POST verb and what is handed in, the query, is always ultimately a string.

  1. https://semaphoreci.com/community/tutorials/testing-services-in-angular-2
  2. https://medium.com/@MatheusCAS/injecting-a-service-into-another-service-in-angular-3b253df5c21
  3. https://blog.angulartraining.com/how-to-write-unit-tests-for-angular-code-that-uses-the-httpclient-429fa782eb15

No comments:

Post a Comment