I am facing a situation in which I need to monitor a method that is invoked after another method is triggered.
Here is the class/method I am testing:
@Injectable()
export class SomeService {
constructor(private customHttpClient: CustomHttpClient) {
}
updateSomethingCool(signerVO: SignerVO): Observable<SignerVO> {
// ...
return this.customHttpClient.withCustomOverrides(new CustomErrorHandlerHttpInterceptorOverride({ passthroughStatusCodes: [BAD_REQUEST, BAD_GATEWAY] }))
.put<SignerVO>(`/my/url/goes/here`, signerVO);
}
}
This class uses CustomHttpClient which has the following structure:
@Injectable()
export class CustomHttpClient extends HttpClient {
private interceptors: HttpInterceptor[] | null = null;
constructor(private injector: Injector,
originalHandler: HttpHandler, private originalBackend: HttpBackend) {
super(originalHandler);
}
public withCustomOverrides(...overrides: CustomHttpInterceptorOverride[]): HttpClient {
// do very customizable things here
return new CustomDelegatingHttpClient(
new CustomHttpInterceptingHandler(this.originalBackend, this.interceptors, overrides));
}
}
export class CustomDelegatingHttpClient extends HttpClient {
constructor(private delegate: HttpHandler) {
super(delegate);
}
}
Below is my approach to performing unit testing on the put
method to ensure it has been called. This requires me to spy on the put
method:
describe(SomeService.name, () => {
let service: SomeService;
let customHttpClient: CustomHttpClient;
let emptySignerVO: SignerVO = new SignerVO();
beforeEach(() => {
customHttpClient= <CustomHttpClient>{};
customHttpClient.put = () => null;
customHttpClient.withCustomOverrides = () => null;
service = new SomeService(customHttpClient);
});
describe('updateSomethingCool', () => {
it('calls put', () => {
spyOn(customHttpClient, 'put').and.stub();
service.updateSomethingCool(emptySignerVO);
expect(customHttpClient.put).toHaveBeenCalled();
});
});
Upon running the test, I encounter the following failure message:
TypeError: Cannot read property 'put' of null
However, I am unsure how to properly define the put
or withCustomOverrides
methods within the beforeEach
section of the test.
Note that CustomHttpClient
serves as an enhanced wrapper class around Angular's HttpClient
offering additional functionalities.
Your assistance is greatly appreciated!