我的问题是:
我正在Nest.js中使用我的自定义日志:
export class ReportLogger extends ConsoleLogger {
verbose(message: string) {
console.log('【Verbose】Reporting', message);
super.verbose.apply(this, arguments);
}
log(message: string) {
console.log('【Log】Reporting', message);
super.log.apply(this, arguments);
}
}和log.interceptor.ts文件:
export class LogInterceptor implements NestInterceptor {
constructor(private reportLogger: ReportLogger) {
this.reportLogger.setContext('LogInterceptor');
}
intercept(context: ExecutionContext, next: CallHandler) {
const http = context.switchToHttp();
const request = http.getRequest();
const now = Date.now();
return next
.handle()
.pipe(
tap(() =>
this.reportLogger.log(
`${request.method} ${request.url} ${Date.now() - now}ms`,
),
),
);
}
}下面是main.ts文件:
async function bootstrap() {
const reportLogger = new ReportLogger();
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
cors: {
origin: ['http://localhost', 'http://localhost:3000'],
credentials: true,
},
bufferLogs: true,
logger: reportLogger,
});
app.useGlobalInterceptors(
new LogInterceptor(reportLogger),
);
setupSwagger(app);
await app.listen(4200);
}当我运行npm run start:dev来运行Nest时,一切都很好。但是,当我在测试中运行npm run test:e2e或npm run test时,它会显示以下错误:
Using the "extends Logger" instruction is not allowed in Nest v8. Please, use "extends ConsoleLogger" instead.
10 | const moduleFixture: TestingModule = await Test.createTestingModule({
11 | imports: [AppModule],
> 12 | }).compile();
| ^
13 |
14 | app = moduleFixture.createNestApplication();
15 | await app.init();我再次阅读了Nest.js文档,并在文档中找到了测井破断变化。但问题是,我已经让我的ReportLogger扩展了ConsoleLogger,为什么这个错误再次显示出来?为什么它只显示在测试中?
发布于 2021-08-07 19:13:45
在将NestJS升级到版本8之后,我也遇到了同样的问题。
后来,我发现包@nestjs/testing已经安装了以前的版本,并且没有升级到最新版本。原因是,以前版本的NestJS测试模块使用的是旧的Logger。
为了解决此问题,只需升级NestJS测试模块即可。
运行以下命令以获取最新版本:
npm i @nestjs/testing@latest或特定版本的
npm i @nestjs/testing@8.0.6 // <--- Change the NestJS version here在此之后,只需再次构建和运行测试用例。
外部链接:
发布于 2021-09-24 19:15:02
即使使用"@nestjs/testing": "^8.0.7",这个问题仍然会发生。
class Logger implements LoggerService { ... }
await Test.createTestingModule({
imports: [ApiModule],
})
.setLogger(new Logger())
.compile();设置记录器实例解决了我的错误。
https://stackoverflow.com/questions/68689281
复制相似问题