在 Vitest 中,如何断言 console.log() 发生了?

bbs*_*nbb 9 vitest

问题就在标题里。对于 Jest 来说就是这样console.log = jest.fn()。如何获取并分析我正在测试的代码的控制台输出?

Yok*_*a59 14

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');
  });
});
Run Code Online (Sandbox Code Playgroud)