Search code examples
typescriptunit-testingnestjsts-mockito

How to mock a named nestjs Logger with ts-mockito


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).


Solution

  • I managed to fix the optional parameter issue by using capture instead of verify e.g. before:

        verify(mockX.getUsers({key: 'val'}) ).once();
    

    after:

        const [opts] = capture(mockX.getUsers).last();
        expect(opts).toEqual({key: 'val'});