Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vitest

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?

like image 350
bbsimonbb Avatar asked Dec 04 '25 00:12

bbsimonbb


1 Answers

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');
  });
});
like image 118
Yokozuna59 Avatar answered Dec 07 '25 16:12

Yokozuna59



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!