I have a very simple interceptor that redirects you when the app is in outage mode
@Injectable()
export class OutageRedirectInterceptor implements NestInterceptor {
constructor(private readonly stateService: StateService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
if (this.stateService.isInOutageMode) {
const res = context.switchToHttp().getResponse<Response>();
res.redirect('/');
}
return next.handle();
}
}
How do I write a unit test for this? I am having trouble mocking the nested context.switchToHttp().getResponse<Response>() call. Here's what I have so far
describe('OutageAccessInterceptor', () => {
let interceptor: OutageRedirectInterceptor;
let stateSvc: StateService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [],
providers: [OutageRedirectInterceptor, StateService],
}).compile();
interceptor = module.get(OutageRedirectInterceptor);
stateSvc = module.get(StateService);
});
it('should redirect when outage mode is ENABLED', () => {
stateSvc.isInOutageMode = true;
const executionCtxMock = mockDeep<ExecutionContext>();
const redirectSpy = jest.spyOn(executionCtxMock.switchToHttp().getResponse<Response>(), 'redirect');
// ^^^^^^^^^^^^
//ERROR "Cannot read properties of undefined (reading 'getResponse')"
const nextMock: CallHandler = {
handle: jest.fn(() => of()),
};
interceptor.intercept(executionCtxMock, nextMock);
expect(nextMock.handle).toHaveBeenCalledWith();
expect(redirectSpy).toHaveBeenCalledWith('/');
});
});