Sea*_*ter 2 testing node.js e2e-testing nestjs
这是我遇到的问题:
我在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
和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`,
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是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);
}
Run Code Online (Sandbox Code Playgroud)
当我npm run start:dev在 dev 上运行 Nest App 时,一切正常。但是当我运行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();
Run Code Online (Sandbox Code Playgroud)
我再次阅读了 Nest.js 文档,并在文档中发现了Logging 的重大更改。但问题是我已经让我的 ReportLogger 扩展了 ConsoleLogger,为什么这个错误又出现了?为什么它只在测试中显示?
小智 9
将 NestJS 升级到版本 8 后,我遇到了同样的问题。
后来,我发现该软件包@nestjs/testing安装了以前的版本,并没有升级到最新版本。原因是,以前版本的 NestJS 测试模块使用的是旧的 Logger。
为了解决这个问题,你只需要升级 NestJS 测试模块。
为最新版本运行此命令:
npm i @nestjs/testing@latest
Run Code Online (Sandbox Code Playgroud)
或特定版本
npm i @nestjs/testing@8.0.6 // <--- Change the NestJS version here
Run Code Online (Sandbox Code Playgroud)
在此之后,只需再次构建并运行测试用例。
外部链接:
| 归档时间: |
|
| 查看次数: |
398 次 |
| 最近记录: |