Home > Software design >  How to mock a named nestjs Logger with ts-mockito
How to mock a named nestjs Logger with ts-mockito

Time:07-05

Our project uses nestjs with mocha, chai and ts-mockito for testing and I can't figure out how to test a named nestjs Logger.

new Logger() can be tested as expected:

describe('basic test', () => {
    it('works', async () => {
        const mockLogger = mock<LoggerService>();
        const moduleRef = await Test.createTestingModule({
            providers: [
                {
                    provide: TestClass,
                    useValue: new TestClass(),
                },
            ],
        })
            .setLogger(instance(mockLogger))
            .compile();

        const unit = moduleRef.get(TestClass);

        unit.log();

        verify(mockLogger.error(anything())).once();
    });
});

class TestClass {
    readonly logger: Logger;
    constructor() {
        this.logger = new Logger();
    }

    public log() {
        this.logger.error(new Error());
    }
}

but using a named logger fails the test:

class TestClass {
    readonly logger: Logger;
    constructor() {
        this.logger = new Logger('name');
    }

    public log() {
        this.logger.error(new Error());
    }
}

with // Expected "error(anything())" to be called 1 time(s). But has been called 0 time(s).

CodePudding user response:

This is due to the way ts-mockito handles optional function arguments. A question on this issue can be found here

Calling

new Logger('name').error(message);

is effectively the same as calling

new Logger().error('message', 'name');

and the mock needs to be changed to reflect this difference in arguments.

Changing

verify(mockLogger.error(anything())).once();

to

verify(mockLogger.error(anything(), anything())).once();

fixes the problem.

  • Related