1

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

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;
    }

现在我正在使用下面的玩笑为这个类编写单元测试。

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被调用,或者如何Rollbar在这个类中模拟。

4

1 回答 1

1

1)在模块中提供您的外部依赖项/库作为可注入令牌

@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();
于 2019-08-06T18:11:28.380 回答