NestJs testing for void super method calls

  javascript, jestjs, nestjs

I have the following service that extends nestjs Logger.

@Injectable({scope:Scope.TRANSIENT})
export class LogService extends Logger {

async log(message: string, context?: string): Promise<void> {
  super.log(message, context);
  super.log(message, context);
  super.log(message, context);
  super.log(message, context);
  super.log(message, context);
}

async debug(message: string, context?: string): Promise<void> {
   super.debug(message, context);
   super.debug(message, context);
   super.debug(message, context);
   super.debug(message, context);
   super.debug(message, context);
}

I have a test class as follows:

describe('LogService', () => {
   let service: Logger;
  const inputMessage = 'message';

beforeEach(async () => {
   const module: TestingModule = await Test.createTestingModule({
   providers: [LogService],
 }).compile();

  service = await module.resolve<LogService>(LogService);
});


 afterEach(() => {
   jest.clearAllMocks();
  });

 // test 1
 it('should call Logger's log method', async () => {
   const loggerSpy = jest.spyOn(Logger.prototype, 'log');
   await service.log(inputMessage);
   expect(loggerSpy).toHaveBeenCalledTimes(5)
 });
 
 // test2
 it('should call Logger's debug method', async () => {
   const loggerSpy = jest.spyOn(Logger, 'debug');
   await service.log(inputMessage);
   expect(loggerSpy).toHaveBeenCalledTimes(5)
});

These 2 tests will pass as shown above, but notice the line jest.spyOn(Logger…) for the 2 tests and they are different.

When I modify the jest spy lines, I get the following issues:

For second test, I tried switching the line to jest.spyOn(Logger.prototype, ‘debug’), and now the expected number of calls is 10

For first test, I tried switching the line to jest.spyOn(Logger, ‘log’), and now the expected number of calls is 0.

What could be causing such inconsistencies between the 2 tests?

Source: Ask Javascript Questions

LEAVE A COMMENT