Jest.js 无法读取未定义的nestjs测试用例nodejs的属性“getRequestId”

bwntbbo3  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(124)

我有一个日志服务

import { Logger } from '@nestjs/common';
import { RequestIdProvider } from "src/common/services/request-id.provider";

export class AppLogger extends Logger {

  constructor(private readonly requestIdProvider: RequestIdProvider) {
    super();
  }

  private formatMessage(message: any[], requestId: string): string {
    const logMessage = message.map((msg) => (typeof msg === 'string' ? msg : JSON.stringify(msg))).join(' ');
    return `[Request ID: ${requestId}] ${logMessage}`;
  }

  log(...messages: any[]) {
    const requestId = this.requestIdProvider.getRequestId();
    super.log(this.formatMessage(messages, requestId));
  }

这里是request-id提供程序

import { REQUEST } from "@nestjs/core";
import { Injectable, Scope, Inject } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class RequestIdProvider {
  constructor(@Inject(REQUEST) private readonly request) { }

  getRequestId(): string {
    return this.request.requestId;
  }
}

在我的测试案例中

describe('MyController', () => {
  let controller: MyController;
  let service: myService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [RolesController],
      providers: [
        MyService, AppLogger, RequestIdProvider,

但我正在面对

● MyController › update › should update a role

    TypeError: Cannot read property 'getRequestId' of undefined
6yoyoihd

6yoyoihd1#

我必须创建appLogger示例

const mockRequestIdProvider: any = {
      getRequestId: jest.fn().mockReturnValue('test-request-id'), // Provide a mock implementation
    };
appLogger = new AppLogger(mockRequestIdProvider);

然后在供应商

{ provide: AppLogger, useValue: appLogger },

相关问题