【问题标题】:Dependency injection issue for `@ntegral/nestjs-sentry` package in nestjs appNestjs 应用程序中`@ntegral/nestjs-sentry` 包的依赖注入问题
【发布时间】:2022-01-15 18:47:38
【问题描述】:

我对 Nestjs 中的这个包 @ntegral/nestjs-sentry 有疑问。我有一个在我的应用程序中使用的自定义记录器

@Injectable()
export class CustomLogger implements LoggerService {
  constructor(@InjectSentry() private readonly client: SentryService) {}

  log(message: any, ...optionalParams: any[]) {
    this.client.instance().captureMessage(message, ...optionalParams);
  }
}

然后我将其注入到用户控制器和 user.controller.spec.ts

describe('UsersController', () => {
  let controller: UsersController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers: [
        CustomLogger,
        UsersService,
        SentryService,
      ],
    }).compile();

    controller = module.get<UsersController>(UsersController);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });
});

我收到此错误

 FAIL  src/users/users.controller.spec.ts (9.449 s)
  ● UsersController › should be defined

    Nest can't resolve dependencies of the CustomLogger (?). Please make sure that the argument Symbol(SentryToken) at index [0] is available in the RootTestModule context.

    Potential solutions:
    - If Symbol(SentryToken) is a provider, is it part of the current RootTestModule?
    - If Symbol(SentryToken) is exported from a separate @Module, is that module imported within RootTestModule?
      @Module({
        imports: [ /* the Module containing Symbol(SentryToken) */ ]
      })

我已尝试将SentryService 添加到规范提供程序,但这并不能解决错误。有没有人遇到过这个问题,你是怎么解决的。

【问题讨论】:

    标签: nest sentry nestjs-sentry


    【解决方案1】:

    我遇到了完全相同的问题。似乎该库对其自己的 Inject 注释使用了不同的标记。通过使用为 SentryService 模拟提供的令牌,我能够在我的测试中修复它。

    import { SENTRY_TOKEN } from '@ntegral/nestjs-sentry';
    
    // ...
    
    const module: TestingModule = await Test.createTestingModule({
      providers: [
      // ...
        {
          provide: SENTRY_TOKEN,
          useValue: { debug: jest.fn() }, // provide SentryService Mock here
        },
      ],
    })
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2021-04-06
      • 2021-11-05
      • 2020-09-09
      • 2021-04-23
      • 1970-01-01
      • 2021-05-29
      • 2023-03-05
      • 2018-12-24
      相关资源
      最近更新 更多