In Vitest, how do I assert that a console.log() happened?
Asked Answered
B

2

12

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?

Brownstone answered 18/4, 2023 at 9:32 Comment(0)
J
17
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');
  });
});
Jumpoff answered 17/5, 2023 at 10:45 Comment(2)
exemplary answerSoracco
how to assert that some console.log contained the string 'hey'?Tennessee
S
2

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

Scarberry answered 29/1 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.