I have an Angular 13 app with a custom HTTP client and an interceptor, which I want to unit test.
base-url.interceptor.ts
:
import { Inject, Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
export const BASE_API_URL = 'BASE_API_URL';
@Injectable()
export class BaseUrlInterceptor implements HttpInterceptor {
constructor(@Inject(BASE_API_URL) private baseUrl: string) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
const apiRequest = request.clone({ url: `${this.baseUrl}${request.url}` });
return next.handle(apiRequest);
}
}
base-url.interceptor.spec.ts
:
import { TestBed } from '@angular/core/testing';
import { ApiHttpService, API_HTTP_INTERCEPTORS } from '../api-http.service';
import { BaseUrlInterceptor, BASE_API_URL } from './base-url.interceptor';
describe('BaseUrlInterceptor', () => {
let interceptor: BaseUrlInterceptor;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
providers: [
ApiHttpService,
{ provide: BASE_API_URL, value: 'http://example.com' },
{ provide: API_HTTP_INTERCEPTORS, useClass: BaseUrlInterceptor, multi: true }
]
});
interceptor = TestBed.inject(BaseUrlInterceptor);
});
it('should be created', () => {
expect(interceptor).toBeTruthy();
});
});
Unfortunately TestBed.inject(BaseUrlInterceptor)
fails to inject an instance of the interceptor. interceptor
is always undefined
. If I workaround this by creating the instance manually new BaseUrlInterceptor('http://example.com');
it works, but other interceptors have further dependencies and I want to use Angulars dependency injection here.
How can I configure the TestBed, so it can successfully create an instance of BaseUrlInterceptor
?
I've created a minimal CodeSandbox which reproduces the problem:
Furthermore I get this error message, when I run the faulty test:
Chrome Headless 98.0.4758.102 (Linux x86_64) BaseUrlInterceptor should be created FAILED
Error: NG0204: unreachable
error properties: Object({ code: 204 })
Error: NG0204: unreachable
at injectableDefOrInjectorDefFactory (node_modules/@angular/core/fesm2015/core.mjs:11494:1)
at providerToFactory (node_modules/@angular/core/fesm2015/core.mjs:11556:1)
at providerToRecord (node_modules/@angular/core/fesm2015/core.mjs:11521:1)
at R3Injector.processProvider (node_modules/@angular/core/fesm2015/core.mjs:11424:1)
at node_modules/@angular/core/fesm2015/core.mjs:11410:1
at node_modules/@angular/core/fesm2015/core.mjs:4162:1
at Array.forEach (<anonymous>)
at deepForEach (node_modules/@angular/core/fesm2015/core.mjs:4162:1)
at R3Injector.processInjectorType (node_modules/@angular/core/fesm2015/core.mjs:11410:1)
at node_modules/@angular/core/fesm2015/core.mjs:11213:1
Error: Expected undefined to be truthy.
at <Jasmine>
at UserContext.<anonymous> (projects/frontend/src/app/core/http/interceptors/base-url.interceptor.spec.ts:21:25)
at ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:1)
at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:287:1)
Chrome Headless 98.0.4758.102 (Linux x86_64): Executed 1 of 1 (1 FAILED) (0.072 secs / 0.056 secs)
TOTAL: 1 FAILED, 0 SUCCESS
CodePudding user response:
You're getting the Error: NG0204: unreachable
because when you're defining the provider for BASE_API_URL
you are using a property value
when it should be useValue
.
{ provide: BASE_API_URL, useValue: 'http://example.com' },
Anyways, even if you fix that, you will get a NullInjectorError
because you are not defining a provider that uses the BaseUrlInterceptor
class as InjectionToken. You're using that class instead as one of the providers for the API_HTTP_INTERCEPTORS
token.
In the context of unit testing the interceptor, you should get rid of the ApiHttpService, and just focus on the interceptor class.
You have two options:
Instantiate the class manually
beforeEach(() => {
interceptor = new BaseUrlInterceptor('http://example.com');
});
Or using the interceptor class as a provider in Testbed
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
providers: [
{ provide: BASE_API_URL, useValue: 'http://example.com' },
BaseUrlInterceptor,
],
});
interceptor = TestBed.inject(BaseUrlInterceptor);
});
cheers