如何使用玩笑模拟第三方库

How to mock third party library using jest

我正在使用 nestjs 开发 node.js 应用程序 我有一个名为 LoggerService 的 class,如下所示

export class LoggerService {

    private logger: Rollbar;

    constructor() {
        this.logger = this.setupLogger();
    }

    critical(...args: Array<string | Error | object | Date | any[]>) {
        this.logger.error(...args);
    }

    private setupLogger(): Rollbar {
        if (this.logger == null) {

            this.logger = new Rollbar({
                accessToken: 'token',
                environment: 'dev',
                captureUncaught: true,
                captureUnhandledRejections: true,
            });

        }

        return this.logger;
    }

现在我正在为这个class编写单元测试,如下所示。

describe('LoggerService.log', () => {
  let service: LoggerService;

  beforeEach(async () => {

    const module: TestingModule = await Test.createTestingModule({
      providers: [LoggerService],
    }).compile();

    service = module.get<LoggerService>(LoggerService);
  });

  it('critical', () => {
    service.critical('error','message');
    expect(???).toHaveBeenCalledWith('error', 'message')
  })

);

我的问题是如何检查(预期)是否调用了 logger.error,或者如何在此 class.

中模拟 Rollbar

1) 提供您的外部 dependency/library 作为模块中的可注入令牌

@Module({
  providers: [
    {
      provide: 'Rollbar',
      useFactory: async (configService: ConfigService) => new Rollbar({
                accessToken: configService.accessToken,
                environment: configService.environment,
                captureUncaught: true,
                captureUnhandledRejections: true,
            }),
      inject: [ConfigService],
    },
  ]

2) 将其注入您的 LoggerService 而不是创建它

export class LoggerService {
    constructor(@Inject('Rollbar') private logger: Rollbar) {
    }

3) 现在您可以在测试中模拟您的依赖关系

const module: TestingModule = await Test.createTestingModule({
  providers: [
    LoggerService,
    { provide: 'Rollbar', useFactory: rollbarMockFactory },
  ],
}).compile();