nestjs Пример тест для пользовательского ExceptionFilter
Primary tabs
Описание проблемы
Инъекция в контроллер и один из методов, использующий фильтр выглядели так:
export class MyController {
constructor(
private readonly someService: SomeService,
@InjectPinoLogger(MyController.name) private readonly logger: PinoLogger,
) {}
// ..........
@Post('share')
@UseFilters(DataExceptionFilter)
async share(
@WithUserInfo() userInfo: UserInfo,
@Body(new JoiValidationPipe(someShareDto))
{ detailsId, usersIds }: SomeShareDto,
): Promise<ScenarioSaveResponse> {
// код метода
При этом сам фильтр имел такой конструктор:
@Catch()
export class DataExceptionFilter implements ExceptionFilter {
constructor(private readonly logger: PinoLogger) {}
-- т.е. требовал на вход параметр типа PinoLogger
Текст-шаблон ошибки:
Nest can't resolve dependencies of the ... (?). Please make sure that the argument ... at index [0] is available in the RootTestModule context.
Potential solutions:
- If ... is a provider, is it part of the current RootTestModule?
- If ... is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing ... */ ]
})
Реальный текст в нашем случае:
Nest can't resolve dependencies of the DataExceptionFilter (?). Please make sure that the argument PinoLogger at index [0] is available in the RootTestModule context.
Potential solutions:
- If PinoLogger is a provider, is it part of the current RootTestModule?
- If PinoLogger is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing PinoLogger */ ]
})
Возможное решение
В файле ...controller.spec.ts, описывающем тест для данного контроллера добавить в providers:
import { PinoLogger, getLoggerToken } from 'nestjs-pino';
import { PinoLoggerFake } from '../../services/_fake/pinoLogger.service.fake';
// ..........
describe('MyController', () => {
let controller: MyController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [MyController],
providers: [
// ........
// ........
{
provide: PinoLogger,
useClass: PinoLoggerFake,
},
],
}).compile();
Где PinoLoggerFake может быть реализован как:
export class PinoLoggerFake {
public debug(): void {
//fake method implementation
}
public warn(): void {
//fake method implementation
}
public info(): void {
//fake method implementation
}
}- Log in to post comments
- 1260 reads