The question's in the title. With Jest it was console.log = jest.fn()
. How do I get and analyse the console output of the code I'm testing?
In Vitest, how do I assert that a console.log() happened?
import { afterAll, describe, it, expect, vi } from 'vitest';
describe('should mock console.log', () => {
const consoleMock = vi.spyOn(console, 'log').mockImplementation(() => undefined);
afterAll(() => {
consoleMock.mockReset();
});
it('should log `sample output`', () => {
console.log('sample output');
expect(consoleMock).toHaveBeenCalledOnce();
expect(consoleMock).toHaveBeenLastCalledWith('sample output');
});
});
exemplary answer –
Soracco
how to assert that some console.log contained the string 'hey'? –
Tennessee
Thanks a lot for your answer @Yokozuna59!
For others, if you still want to see the console log output, just define:
const consoleSpy = vi.spyOn(console, 'log')
without the mockImplementation()
.
© 2022 - 2024 — McMap. All rights reserved.