I wrote an own CacheInterceptor to cache POST requests as well and take the Accept-Language header into account. Of course I want to unit test it, but I don't know how to properly do so, since the trackBy method needs an ExecutionContext and the method uses the httpAdapterHost and reflector fields.
Has anybody done this before and knows how to achieve full test coverage?
EDIT: Here is the code of the CacheInterceptor
import {
CACHE_KEY_METADATA,
CacheInterceptor,
ExecutionContext,
Injectable,
} from '@nestjs/common';
import { createHash } from 'crypto';
@Injectable()
export class MyCacheInterceptor extends CacheInterceptor {
trackBy(context: ExecutionContext): string | undefined {
const httpAdapter = this.httpAdapterHost.httpAdapter;
const cacheMetadata = this.reflector.get(CACHE_KEY_METADATA, context.getHandler());
const request = context.switchToHttp().getRequest();
return [
cacheMetadata,
httpAdapter.getRequestUrl(request),
JSON.stringify(request.body),
request.headers['accept-language'],
]
.reduce(
(hash, somethingToHash) => (
hash.update(
somethingToHash
? Buffer.from(somethingToHash)
: Buffer.alloc(0)
)
),
createHash('md5'),
)
.digest('hex');
}
}