4

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?

bbsimonbb
  • 27,056
  • 15
  • 80
  • 110

1 Answers1

4
import { afterAll, describe, expect, vi } from 'vitest';

describe('should mock console.log', () => {
  const consoleMock = vi.spyOn(console, 'log').mockImplementation(() => {});

  afterAll(() => {
    consoleMock.mockReset();
  });

  test('should log `sample output`', () => {
    console.log('sample output');
    expect(consoleMock).toHaveBeenCalledOnce();
    expect(consoleMock).toHaveBeenLastCalledWith('sample output');
  });
});
Yokozuna59
  • 66
  • 1
  • 3