Vitest Preview

website·Indexed 32 days ago

https://www.vitest-preview.com

A visual testing tool for front-end developers that captures DOM states for debugging. It features a dedicated dashboard web server and core APIs including debug(), watch(), and configure(), with automatic modes for previewing failed tests or DOM changes.

Tokens
3.4K
Snippets
24
Records
29
Agent score
61%

What's inside Vitest Preview

  1. Overview of Vitest Preview

    Vitest Preview is a tool built on top of Vite that allows developers to preview Vitest tests visually in a browser. It eliminates the need to debug by reading cryptic HTML output in the terminal, enabling developers to see the actual UI and watch rendered output changes in real-time as tests are written.
  2. Overview of Vitest Preview Automatic Mode

    Automatic Mode in Vitest Preview allows developers to capture and preview the DOM state automatically without inserting manual debug() calls into tests. This provides immediate visual feedback during critical moments of test execution.
  3. Capture DOM state for visual inspection using debug

    The debug function is the core API of Vitest Preview. It captures the current state of the DOM and makes it available for preview in the browser via the Vitest Preview server.

    Key behaviors:

    • Call debug() at the specific point in your test where you want to capture the DOM state.
    • You can call debug() multiple times within a single test to capture different states; however, the preview server will only display the output of the most recent call.
    import { debug } from 'vitest-preview';
    
    test('renders correctly', () => {
      render(<YourComponent />);
    
      // Call debug to capture the current DOM state
      debug();
    });
  4. Include CSS in Vitest Preview via direct imports

    Instead of using the configure function's externalCss option, it is recommended to import CSS files directly in your test setup file. This ensures the CSS files are processed by Vite and correctly included in the preview.
    // setup.ts or setup.js
    import { configure } from 'vitest-preview';
    
    // Import CSS files directly to ensure Vite processing
    import './styles/global.css';
    import './public/index.css';
    import './node_modules/@your-ui-lib/dist/styles.css';
  5. Automatically capture DOM changes with watch

    The watch function automatically captures DOM changes and triggers the debug() function. This is useful for visualizing UI changes across multiple interactions in a test without manually inserting debug() calls. It is particularly effective for debugging complex tests with frequent DOM updates.
    import { watch } from 'vitest-preview';
    
    let stopWatching;
    
    beforeEach(() => {
      // Start watching for DOM changes
      stopWatching = watch();
    });
    
    afterEach(() => {
      // Stop watching when done
      stopWatching();
    });
  6. Enable automatic DOM preview for all tests

    The autoPreviewOnDomChanges function automatically captures and previews the DOM state whenever changes occur by using a MutationObserver. It is typically called in a test setup file to enable this behavior globally across all tests, starting the watch at the beginning of each test and stopping it at the end.
    // src/test/setup.ts or your test setup file
    import { autoPreviewOnDomChanges } from 'vitest-preview';
    
    // Enable automatic preview on DOM changes for all tests
    autoPreviewOnDomChanges();
  7. Automatically preview failed tests using Custom Fixtures

    Use custom fixtures to add automatic debugging without modifying your global cleanup strategy. This approach requires you to use a custom test and it import instead of the standard Vitest imports in your test files.
    // utils/vitest-utils.ts
    import { test as baseTest } from 'vitest';
    import { debug } from 'vitest-preview';
    
    export * from 'vitest';
    
    const test = baseTest.extend({
      automaticDebugOnFail: [
        async ({ task }, use) => {
          await use(undefined);
          if (task.result?.state === 'fail') {
            debug();
          }
        },
        { auto: true },
      ],
    });
    
    const it = test;
    export { test, it };
    
    // --- In your test file ---
    // import { test, describe, expect } from './utils/vitest-utils';
  8. Preview test UI using the debug() function

    To visualize a specific state in your tests, import and call the debug() function. Then, run the vitest-preview CLI and execute your tests. The UI will be available at http://localhost:5006.
    import { debug } from 'vitest-preview';
    
    describe('App', () => {
      it('should work as expected', () => {
        render(<App />);
        debug(); // Capture UI state here
      });
    });
    # Run the dashboard
    npm run vitest-preview
  9. Automatically preview failed tests using the onTestFinished hook

    The recommended way to enable global automatic debugging is using the onTestFinished hook within a beforeEach block. This captures the DOM state immediately upon failure before the cleanup process runs.

    Crucial Requirement: If using Testing Library, you must disable automatic cleanup (e.g., remove globals: true in vitest.config.ts or remove afterEach(cleanup) from setup files) to prevent the DOM from being destroyed before debug() is called.

    // setupFiles.ts
    import { beforeEach } from 'vitest';
    import { cleanup } from '@testing-library/react';
    import { debug } from 'vitest-preview';
    
    beforeEach((ctx) => {
      ctx.onTestFinished(({ task }) => {
        if (task?.result?.state === 'fail') {
          // Preview the failed test in the Vitest Preview Dashboard
          debug();
        }
        // Perform cleanup after capturing the DOM state
        cleanup();
      });
    });
  10. Configure external CSS files in Vitest Preview

    Use the configure function to specify an array of CSS file paths that should be included in the Vitest Preview. Paths must be relative to the current working directory (typically the project root), not the test setup file.

    Note: The Vitest Preview Dashboard does not automatically refresh when these files change; a manual refresh is required to see updates.

    // setup.ts or setup.js
    import { configure } from 'vitest-preview';
    
    configure({
      externalCss: [
        './styles/global.css',
        './public/index.css',
        './node_modules/@your-ui-lib/dist/styles.css',
      ],
    });
  11. Use Auto Preview on DOM Changes to monitor UI transitions

    Auto Preview on DOM Changes continuously monitors the DOM and captures the state whenever a modification occurs. This is best for observing real-time UI transitions, debugging complex interactions with multiple updates, or visually testing animations and dynamic content.
    import { autoPreviewOnDomChanges } from 'vitest-preview';
    
    autoPreviewOnDomChanges();
  12. Install vitest-preview

    Install vitest-preview as a development dependency using your preferred package manager.
    # npm
    npm install --save-dev vitest-preview
    
    # yarn
    yarn add -D vitest-preview
    
    # pnpm
    pnpm add -D vitest-preview