Ask Your Question
3

What is the method to simulate the NestJS internal Logger using Jest?

asked 2021-07-25 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-06-07 12:00:00 +0000

plato gravatar image

To simulate the NestJS internal Logger using Jest, you can use the jest.spyOn() method to create a spy on the LoggerService class.

Here is an example of how you can test a method that uses the NestJS internal Logger:

import { Test, TestingModule } from '@nestjs/testing';
import { MyService } from './my.service';
import { LoggerService } from '@nestjs/common';

describe('MyService', () => {
  let service: MyService;
  let loggerSpy: jest.SpyInstance;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        MyService,
        {
          provide: LoggerService,
          useValue: {
            debug: jest.fn(),
            error: jest.fn(),
            log: jest.fn(),
            verbose: jest.fn(),
            warn: jest.fn(),
          },
        },
      ],
    }).compile();

    service = module.get(MyService);
    loggerSpy = jest.spyOn(service.logger, 'log');
  });

  afterEach(() => {
    loggerSpy.mockClear();
  });

  it('should call the log method of the logger', () => {
    service.myMethod();

    expect(loggerSpy).toHaveBeenCalledWith('My message');
  });
});

In this example, we create a spy on the log method of the LoggerService, and use it to verify that the method myMethod calls the logger with the expected message. We also clear the spy after each test to make sure it doesn't interfere with the next test.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-25 11:00:00 +0000

Seen: 10 times

Last updated: Jun 07 '21