How to debug Angular component test Dependency Injection chain

When running ng test (Angular component testing) and you get this type of error:

[Service1 -> Service2 -> Service3]: NullInjectorError: No provider for Service3!

And you dont really understand which component, service or directive that is starting this DI chain. Here is a way to debug and hopefully find the source of the problem:

In Edge/Chrome: when in karma runner page, open devtools (f12), on source tab, select both “Pause on uncaught/caught exceptions”

Reload the test, step into a few times, you should be able to get the call stack as in picture above. Here we can deduce that DI chain starts with a component html template, which uses a translate directive in markup, which calls DictionaryService which calls UserAppDataQueryService which calls AuthenticationService.

Tip: run all spec files below a certain folder like this:

ng test --include "src/app/myarea/**/*.spec.ts" --browsers=Edge

Tip2: run a single spec file:

ng test --include "src/app/myarea/**/mytest.component.spec.ts" --browsers=Edge

 

Leave a Reply

Your email address will not be published. Required fields are marked *