All quizzesMedium
Mocking & E2E Tests — Series 2
Preview — 3 of 10 questions
What does this accomplish?
javascript
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
.overrideGuard(JwtAuthGuard)
.useValue({ canActivate: (ctx: ExecutionContext) => {
ctx.switchToHttp().getRequest().user = { id: 'u_1', roles: ['admin'] };
return true;
}})
.compile();AIt disables all guards in the application, including globally registered ones
BIt replaces that specific guard wherever it is bound, so the endpoint tests exercise the handler's behaviour with a known user instead of going through a real login on every request
CIt removes the guard's metadata, so the route becomes public
DIt only affects guards bound with @UseGuards(), not those registered through APP_GUARD
Why did validation not run?
javascript
app = moduleRef.createNestApplication();
await app.init();
const res = await request(app.getHttpServer()).post('/cats').send({ name: 123 });
// expected 400, received 201AcreateNestApplication() disables validation deliberately, to keep tests fast
Bsupertest bypasses the enhancer pipeline and calls handlers directly
CThe DTO must be re-registered on the testing module for its decorators to apply
DGlobal pipes registered in main.ts with app.useGlobalPipes(...) are not part of the module graph, so a test that builds its own application never applies them — either register them in the test too, or move the registration into a module as an APP_PIPE provider so it travels with the graph
Why is getRepositoryToken(Cat) needed?
javascript
const moduleRef = await Test.createTestingModule({
providers: [
CatsService,
{ provide: getRepositoryToken(Cat), useValue: { findOneBy: jest.fn(), save: jest.fn() } },
],
}).compile();A@InjectRepository(Cat) injects under a generated token derived from the entity, not under the Repository class — so the override must use the same token, which this helper computes
BIt converts the mock object into a real Repository instance
CIt registers the entity with the test's data source
DIt is optional; providing Repository directly works identically
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.