All quizzesHard
Advanced Testing
Preview — 3 of 10 questions
To unit-test an interceptor's intercept(context, next), what do you pass as next?
javascript
import { of } from 'rxjs';
import { CallHandler, ExecutionContext } from '@nestjs/common';
const next: CallHandler = { handle: () => of({ raw: true }) };
const context = {} as ExecutionContext;
interceptor.intercept(context, next).subscribe((result) => {
expect(result).toEqual({ data: { raw: true } }); // after a wrapping interceptor
});AA mock CallHandler whose handle() returns an observable, e.g. { handle: () => of(value) }
BThe real route handler from the controller
CA Promise that resolves to the value
Dnull, because interceptors don't use next
What does an exception filter test need to mock on ArgumentsHost?
javascript
import { ArgumentsHost, HttpException } from '@nestjs/common';
const json = jest.fn();
const status = jest.fn().mockReturnValue({ json });
const host = {
switchToHttp: () => ({ getResponse: () => ({ status }), getRequest: () => ({ url: '/x' }) }),
} as unknown as ArgumentsHost;
filter.catch(new HttpException('Nope', 400), host);
expect(status).toHaveBeenCalledWith(400);AswitchToHttp() returning getResponse()/getRequest() so you can assert the filter sets the right status and JSON body
BswitchToWs() only
CThe Prisma client
DThe Jest config object
What is a clean way to mock a Repository<Entity> for a service test?
javascript
import { getRepositoryToken } from '@nestjs/typeorm';
import { createMock } from '@golevelup/ts-jest';
import { Repository } from 'typeorm';
const moduleRef = await Test.createTestingModule({
providers: [
UserService,
{ provide: getRepositoryToken(User), useValue: createMock<Repository<User>>() },
],
}).compile();AConnect to the real database in unit tests
BUse @golevelup/ts-jest's createMock<Repository<Entity>>() (or a manual object of jest.fn()s) and bind it via getRepositoryToken(Entity)
CSubclass Repository and override every method by hand each test
DPass undefined and hope the service handles it
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.