All quizzesMedium
Mocking & E2E Tests
Preview — 3 of 10 questions
You mock a repository with { provide: UserRepo, useValue: { findOne: jest.fn() } }. How do you make findOne return a user in one specific test?
javascript
const repo = moduleRef.get<UserRepo>(UserRepo) as jest.Mocked<UserRepo>;
repo.findOne.mockResolvedValue({ id: '1', name: 'Ada' });
const result = await service.getUser('1');
expect(result.name).toBe('Ada');AReassign the whole provider inside the test
BUse jest.mock('UserRepo')
CEdit the useValue object literal at runtime
DCall repo.findOne.mockResolvedValue(user) (or mockReturnValue) on the retrieved mock before acting
To unit-test a CanActivate guard, what do you typically provide?
javascript
import { ExecutionContext } from '@nestjs/common';
const context = {
switchToHttp: () => ({ getRequest: () => ({ headers: { authorization: 'Bearer ok' } }) }),
} as unknown as ExecutionContext;
expect(guard.canActivate(context)).toBe(true);AA real HTTP request from a browser
BNothing; guards can't be unit-tested
CA mocked ExecutionContext whose switchToHttp().getRequest() returns a crafted request object
DA full Nest application bootstrapped with app.listen()
How do you test a custom PipeTransform?
javascript
import { ArgumentMetadata, BadRequestException } from '@nestjs/common';
const meta: ArgumentMetadata = { type: 'body', metatype: String, data: '' };
expect(pipe.transform('42', meta)).toBe(42);
expect(() => pipe.transform('nope', meta)).toThrow(BadRequestException);AInstantiate the pipe and call pipe.transform(value, metadata) directly, asserting the transformed value or thrown error
BRegister it globally and send HTTP requests only
CPipes are internal and cannot be invoked directly
DReplace it with a guard
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.