简体   繁体   中英

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). // Expected "error(anything())" to be called 1 time(s). But has been called 0 time(s).

I managed to fix the optional parameter issue by using capture instead of verify eg before:

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

after:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM