1

I have setup an angular testbed and I noticed i forgot to provide a service to be injected into my interceptor, so it broke.

The problem is I didn't get any feedback or errors from the testbed, is there are way to validate that all is well ?

for example I am doing this

TestBed.configureTestingModule({
  imports: [HttpClientTestingModule, HttpClientModule],
  providers: [
    {
      multi: true,
      provide: HTTP_INTERCEPTORS,
      useClass: BaseRefInterceptor
    }
  ]
})

The problem above is that the BaseRefInterceptor required a logging provider that I forgot to provide but nothing gave an error just some of my tests failed - but the failure in the tests didn't point to the inteceptor not being able to be constructed.

I was hoping for an error saying, missing injector or something similar

Any idea how to do this ?

Martin
  • 161
  • 1
  • 8

1 Answers1

1

This is not the way to go with unit testing. The unit test are used to isolate the functionality of the current piece of software you are trying to unit test.

Please look here for an excellent answer on unit testing with dependencies

There is no way to do this as this is not the right/intended way to go. What you need to do is mock the BaseRefInterceptor functionality and return whatever data you want to. Especially because another day you will add another dependency and there is no way for the framework to know you did it and shouldn't even if yo find a workaround for this.

Example:

const baseRefInterceptorSpyObj = jasmine.createSpyObj('BaseRefInterceptor', ['methodA']);
TestBed.configureTestingModule({
  imports: [HttpClientTestingModule, HttpClientModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useValue: baseRefInterceptorSpyObj
    }
  ]
})

Check for more information here on spies and SpyObj

Athanasios Kataras
  • 20,791
  • 3
  • 24
  • 45
  • But this is my subject under test, i.e. my tests are testing the interceptors, if I spy it / mock it - then how am even testing (SUT). I mean, any dependencies, for example the logger should be mocked and added to the configureTestingModule - so the mocks get injected into the interceptor. Maybe I am not following, but if I mock / spy on the BaseRefInterceptor - then I am not testing it ... I am testing an mocked implementation. – Martin Oct 27 '19 at 11:22
  • What i am doing is making calls using the httpclient i.e httpClient.get(url).subscribe() and checking the httpTestingController.expectOne(url) – Martin Oct 27 '19 at 11:24
  • so I am not hitting anything live, so I am mocking the logger dependency and also not making real http calls. It was working before but I added a dependency. I am still a little confused, if i mock the SUT then I am not testing it – Martin Oct 27 '19 at 11:25