Test Vue AI Components Without Calling a Real LLM in Every Test

Your continuous integration pipeline is green, your component tests run in seconds, and your component library is pristine. Then, someone updates a prompt template in an AI-powered Vue component, adds a multi-step tool-calling agent loop, or tweaks a streaming response handler. Suddenly, your test suite starts hammering the OpenAI or Anthropic API.

Within minutes, your CI bills spike, your tests become flaky because of rate limits or minor model output variations, and your local test suite crawls to a halt because it is waiting on network sockets instead of local DOM assertions.

If you are building modern Vue 3 applications that incorporate Large Language Models—whether through direct API integration, composables like useAI, or specialized UI components like generative text areas, streaming chat interfaces, and structured data extractors—testing them against a real LLM is an anti-pattern. It introduces non-determinism, network latency, external dependencies, and unnecessary costs into your testing pipeline.

This guide explores how to test Vue AI components effectively and deterministically without calling a real LLM in every test.


📋 Table of Contents


The Real Problem With LLM Integration Testing

When developers first start building AI-enhanced Vue components, they usually write tests that look something like this: mount the component, type a query, click the submit button, and assert that the assistant responds. Under the hood, Pinia or a composable makes an axios or fetch call to https://api.openai.com/v1/chat/completions.

This approach breaks down across several dimensions:

  1. Determinism: LLMs are probabilistic. Even with temperature: 0, models occasionally update their internal weights, change punctuation, or return slightly different wording. Your assertions will eventually fail for reasons entirely unrelated to your Vue code.
  2. Speed: Network round-trips to an external API take anywhere from 500ms to several seconds. Multiply that by a test suite of 300 component tests, and your test run becomes unacceptably slow.
  3. Cost: Hitting commercial APIs during local test runs and PR builds wastes money.
  4. Environment Isolation: Tests should run offline. Requiring an active internet connection and valid production API keys in .env.test is a security risk and an infrastructure hurdle.

To solve this, we need to decouple our Vue component layer from the transport and provider layers. Let's look at how to implement this across 7 distinct patterns.


1. Intercepting Network Transports via MSW (Mock Service Worker)

Scenario: Your Vue component uses standard fetch requests inside a useCompletion composable to communicate with an internal API route (e.g., /api/ai/chat) that proxies requests to an LLM provider.

Why it matters: Mocking global.fetch or axios using basic test framework stubs often misses edge cases in headers, request body serialization, or stream handling. Furthermore, it tightly couples your test assertions to internal implementation details of how network requests are dispatched.

Solution: Use Mock Service Worker (MSW) to intercept HTTP requests at the network level. MSW intercepts requests whether they originate from browser-based Vitest browser mode or Node-based Vitest runs using happy-dom or jsdom.

Code:

// tests/mocks/handlers.ts
import { http, HttpResponse } from 'msw'

export const handlers = [
  http.post('/api/ai/chat', async ({ request }) => {
    const body = (await request.json()) as { prompt: string }

    // Optional: Return dynamic mock responses based on input
    if (body.prompt.includes('error')) {
      return new HttpResponse(
        JSON.stringify({ error: 'Rate limit exceeded' }),
        { status: 429, headers: { 'Content-Type': 'application/json' } }
      )
    }

    return HttpResponse.json({
      id: 'chatcmpl-mock-123',
      object: 'chat.completion',
      choices: [
        {
          index: 0,
          message: {
            role: 'assistant',
            content: 'Hello! I am your mock AI assistant.'
          },
          finish_reason: 'stop'
        }
      ]
    })
  })
]
// tests/components/AIChatBox.spec.ts
import { mount } from '@vue/test-utils'
import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest'
import { setupServer } from 'msw/node'
import { handlers } from '../mocks/handlers'
import AIChatBox from '@/components/AIChatBox.vue'

const server = setupServer(...handlers)

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

describe('AIChatBox.vue', () => {
  it('sends prompt and renders assistant response', async () => {
    const wrapper = mount(AIChatBox)

    const input = wrapper.find('textarea[data-testid="prompt-input"]')
    await input.setValue('Hello AI')

    const submitBtn = wrapper.find('button[data-testid="submit-btn"]')
    await submitBtn.trigger('click')

    // Wait for async DOM update
    await wrapper.vm.$nextTick()
    
    // Allow pending promises to resolve
    await new Promise((resolve) => setTimeout(resolve, 50))

    expect(wrapper.find('.message-assistant').text()).toContain(
      'Hello! I am your mock AI assistant.'
    )
  })
})

Why this works: MSW operates at the network boundary. Your Vue component and composables remain completely unaware that they aren't talking to a live backend. If you later refactor your composable from fetch to ofetch or ky, your MSW tests continue to pass without modification.

💡 Practical note: When testing streaming endpoints with MSW, ensure your mock handler returns a ReadableStream rather than a standard JSON payload if your component relies on Server-Sent Events (SSE).


2. Composable Dependency Injection and Mock Providers

Scenario: Your application architecture encapsulates all AI interactions inside custom Vue composables like useOpenAI() or useAnthropic(), which are consumed across dozens of components.

Why it matters: Intercepting HTTP requests works well for REST endpoints, but modern AI features often rely on SDKs (like @google/genai or @ai-sdk/vue) that manage complex state machines, connection pooling, and tool execution internally, making network-level mocking brittle.

Solution: Leverage Vue's Provide/Inject mechanism combined with factory functions or TypeScript interfaces to swap out the entire AI provider implementation during testing.

Code:

// src/symbols/aiKey.ts
import { InjectionKey } from 'vue'

export interface AIProviderService {
  generateText(prompt: string): Promise<string>
  streamText(prompt: string, onChunk: (chunk: string) => void): Promise<void>
}

export const AI_PROVIDER_KEY: InjectionKey<AIProviderService> = Symbol('AIProvider')
// src/composables/useAI.ts
import { inject } from 'vue'
import { AI_PROVIDER_KEY, AIProviderService } from '@/symbols/aiKey'

export function useAI() {
  const provider = inject(AI_PROVIDER_KEY)
  if (!provider) {
    throw new Error('AIProvider not provided! Did you forget to install the plugin?')
  }
  return provider
}
// tests/components/AIGenerator.spec.ts
import { mount } from '@vue/test-utils'
import { describe, it, expect, vi } from 'vitest'
import AIGenerator from '@/components/AIGenerator.vue'
import { AI_PROVIDER_KEY, AIProviderService } from '@/symbols/aiKey'

describe('AIGenerator.vue with Injected Provider', () => {
  it('displays generated content from mock service', async () => {
    // Create a mock implementation of the service
    const mockAIProvider: AIProviderService = {
      generateText: vi.fn().mockResolvedValue('Mocked AI Output for Tests'),
      streamText: vi.fn().mockImplementation(async (_, cb) => {
        cb('Chunk 1 ')
        cb('Chunk 2')
      })
    }

    const wrapper = mount(AIGenerator, {
      global: {
        provide: {
          [AI_PROVIDER_KEY as symbol]: mockAIProvider
        }
      }
    })

    await wrapper.find('button.generate').trigger('click')
    await wrapper.vm.$nextTick()

    expect(wrapper.find('.output').text()).toBe('Mocked AI Output for Tests')
    expect(mockAIProvider.generateText).toHaveBeenCalledTimes(1)
  })
})

Why this works: Dependency injection decouples the UI component from both the network transport and the concrete SDK implementation. Tests become pure unit tests of component behavior, state management, and user interaction.


3. Pinia Store State Seeding for Complex Chat Interfaces

Scenario: Your application features a multi-threaded chat sidebar, persistent message history, token usage counters, and abort controllers managed globally via a Pinia store (useChatStore).

Why it matters: Mounting a component that triggers store actions which in turn call network services requires extensive mocking setup in every single test file, leading to massive test boilerplate.

Solution: Seed the Pinia store directly with predefined message trees and mock state before mounting the component, testing the UI rendering and user interactions in complete isolation from the network layer.

Code:

// tests/components/ChatSidebar.spec.ts
import { mount } from '@vue/test-utils'
import { describe, it, expect, beforeEach } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useChatStore } from '@/stores/chat'
import ChatSidebar from '@/components/ChatSidebar.vue'

describe('ChatSidebar.vue', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
  })

  it('renders active threads and highlights current session', () => {
    const chatStore = useChatStore()
    
    // Seed store directly
    chatStore.threads = [
      { id: '1', title: 'Vue 3 Composition API', active: false },
      { id: '2', title: 'Pinia vs Vuex Performance', active: true }
    ]

    const wrapper = mount(ChatSidebar, {
      global: {
        plugins: [createPinia()] // Note: ensure pinia instance is shared if needed
      }
    })

    const items = wrapper.findAll('[data-testid="thread-item"]')
    expect(items).toHaveLength(2)
    expect(items[1].classes()).toContain('bg-blue-100')
    expect(items[1].text()).toContain('Pinia vs Vuex Performance')
  })
})

Why this works: By pre-populating the Pinia store, you test the component's reactivity and rendering logic against established data structures. You are testing how the UI reacts to state, not how the state is fetched from an LLM.


4. Simulating ReadableStream Chunks for Real-Time Streaming UI

Scenario: Your AI component displays tokens streaming in real-time word-by-word, complete with a blinking cursor and auto-scrolling container. Testing this requires simulating asynchronous chunk delivery over time.

Why it matters: If you resolve your mock promises synchronously, you miss race conditions, UI flashing during high-frequency DOM updates, and proper cleanup of AbortController listeners.

Solution: Construct a helper utility that returns a custom ReadableStream yielding chunks at controlled intervals using vi.useFakeTimers() or explicit async/await delays.

Code:

// tests/utils/streamMock.ts
export function createMockStream(chunks: string[], delayMs = 10) {
  const encoder = new TextEncoder()
  
  return new ReadableStream({
    async start(controller) {
      for (const chunk of chunks) {
        await new Promise((resolve) => setTimeout(resolve, delayMs))
        controller.enqueue(encoder.encode(chunk))
      }
      controller.close()
    }
  })
}
// tests/components/AIStreamViewer.spec.ts
import { mount } from '@vue/test-utils'
import { describe, it, expect, vi } from 'vitest'
import AIStreamViewer from '@/components/AIStreamViewer.vue'
import { createMockStream } from '../tests/utils/streamMock'

describe('AIStreamViewer.vue', () => {
  it('renders streaming tokens progressively', async () => {
    vi.useFakeTimers()

    const mockStream = createMockStream(['Hello', ' from', ' the', ' stream!'])
    
    // Mock global fetch to return our custom ReadableStream
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
      ok: true,
      body: mockStream
    }))

    const wrapper = mount(AIStreamViewer)

    await wrapper.find('button.start-stream').trigger('click')

    // Advance timers to process chunks
    await vi.runAllTimersAsync()
    await wrapper.vm.$nextTick()

    expect(wrapper.find('.stream-output').text()).toBe('Hello from the stream!')

    vi.useRealTimers()
    vi.unstubAllGlobals()
  })
})

Why this works: Fake timers combined with controlled ReadableStream generators let you exercise time-dependent UI states—such as typing indicators, scroll locking, and cancellation buttons—deterministically without flakiness.


5. Testing Tool-Calling and Function-Execution Loops Locally

Scenario: Your advanced AI component uses LLM function calling. When the user asks "What is the weather in Tokyo?", the model returns a tool call instruction (get_weather), your application executes a local function, feeds the result back to the LLM, and displays the final synthesized answer.

Why it matters: Testing multi-turn agentic loops against a real LLM is painfully slow and expensive because each test run requires 3 to 4 sequential API round-trips.

Solution: Mock the LLM provider to return a predefined sequence of responses: turn one returns a tool call payload; turn two (after receiving tool execution results) returns the final answer.

Code:

// tests/components/AIAgentConsole.spec.ts
import { mount } from '@vue/test-utils'
import { describe, it, expect, vi } from 'vitest'
import AIAgentConsole from '@/components/AIAgentConsole.vue'

describe('AIAgentConsole.vue Tool Execution', () => {
  it('executes local tool when requested by mock model and displays result', async () => {
    let callCount = 0

    const mockAgentService = {
      chat: vi.fn().mockImplementation(async (messages) => {
        callCount++
        if (callCount === 1) {
          // First turn: Model requests tool execution
          return {
            role: 'assistant',
            toolCall: {
              name: 'get_stock_price',
              arguments: { symbol: 'VUE' }
            }
          }
        } else {
          // Second turn: Model synthesizes final answer using tool output
          return {
            role: 'assistant',
            content: 'The current stock price of VUE is $142.50.'
          }
        }
      })
    }

    const wrapper = mount(AIAgentConsole, {
      global: {
        provide: {
          // Using our injection key pattern from Section 2
          'AIProvider': mockAgentService
        }
      }
    })

    await wrapper.find('input[data-testid="query"]').setValue('Check VUE stock')
    await wrapper.find('button[data-testid="send"]').trigger('click')

    // Wait for multi-turn async loop to settle
    await new Promise((resolve) => setTimeout(resolve, 100))
    await wrapper.vm.$nextTick()

    // Verify UI reflects both tool execution log and final answer
    expect(wrapper.find('.tool-execution-log').text()).toContain('get_stock_price(VUE)')
    expect(wrapper.find('.final-response').text()).toContain('$142.50')
    expect(mockAgentService.chat).toHaveBeenCalledTimes(2)
  })
})

Why this works: Simulating multi-turn conversation state locally proves that your event handling, tool registry mapping, and iterative UI updates function correctly without relying on non-deterministic LLM reasoning capabilities.


6. Snapshot Testing AI-Generated Markdown and Custom Renderers

Scenario: Your AI component parses raw markdown, syntax-highlights code blocks, renders LaTeX math formulas, and formats custom HTML custom tags returned by the LLM.

Why it matters: Slight variations in regex matching or markdown parser plugins can corrupt rendered DOM trees, causing layout breaks in production.

Solution: Use deterministic mock payloads containing complex formatting structures and assert against component snapshots or precise element selectors.

Code:

// tests/components/AIMarkdownRenderer.spec.ts
import { mount } from '@vue/test-utils'
import { describe, it, expect } from 'vitest'
import AIMarkdownRenderer from '@/components/AIMarkdownRenderer.vue'

describe('AIMarkdownRenderer.vue', () => {
  it('correctly formats markdown code blocks and callouts', () => {
    const markdownPayload = `
### Summary
Here is your code:
\`\`\`typescript
const greeting: string = 'Hello Vue';
console.log(greeting);
\`\`\`
> ⚠️ Important note: Watch out for reactivity loss.
    `.trim()

    const wrapper = mount(AIMarkdownRenderer, {
      props: {
        content: markdownPayload
      }
    })

    // Assert structural integrity rather than flaky string matching
    expect(wrapper.find('h3').text()).toBe('Summary')
    expect(wrapper.find('pre code.language-typescript').exists()).toBe(true)
    expect(wrapper.find('blockquote').text()).toContain('Important note')
    expect(wrapper.html()).toMatchSnapshot()
  })
})

Why this works: By fixing the input payload to a comprehensive markdown string, you guarantee 100% test determinism while thoroughly validating your custom markdown plugins, syntax highlighters, and DOM sanitizers.


7. Contract Testing the Real LLM in Isolation

Scenario: You have eliminated LLM calls from your everyday unit and component test suites, but you still need assurance that the real API hasn't changed its response schema or dropped support for specific structured output formats.

Why it matters: Mocking everything gives you speed, but it can create a false sense of security if your mock payloads diverge from actual provider responses over time.

Solution: Write a dedicated Integration / Contract Test suite that runs nightly or manually (never on every PR or local commit) against the live LLM API using real API keys stored in encrypted CI secrets.

Code:

// tests/contracts/openai-contract.spec.ts
import { describe, it, expect } from 'vitest'
import { OpenAI } from 'openai'

// Conditionally skip unless running in contract test mode
const runContractTests = process.env.RUN_CONTRACT_TESTS === 'true'

describe.skipIf(!runContractTests)('LLM Contract Tests', () => {
  const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })

  it('conforms to expected JSON schema output for structured extraction', async () => {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: 'Extract name: John Doe, age: 30 as JSON.' }],
      response_format: { type: 'json_object' }
    })

    const content = response.choices[0].message.content
    expect(content).toBeDefined()

    const parsed = JSON.parse(content!)
    expect(parsed).toHaveProperty('name', 'John Doe')
    expect(parsed).toHaveProperty('age')
    expect(typeof parsed.age).toBe('number')
  })
})

Why this works: Separating fast component tests from slow, metered contract tests gives you the best of both worlds: lightning-fast local feedback loops during development, combined with automated upstream API schema verification in your deployment pipeline.


Choosing the Right Mocking Strategy

Strategy Speed Setup Complexity Best Used For
1. MSW Network Interception Fast (~5ms) Medium Components making direct fetch/axios calls to backend API routes
2. Composable Dependency Injection Instant (<1ms) Low Large component libraries relying on composable abstractions (useAI())
3. Pinia Store Seeding Instant (<1ms) Low Complex multi-threaded chat interfaces and global application state
4. ReadableStream Simulation Fast (~10ms) Medium Real-time streaming token renderers, auto-scroll, and abort controllers
5. Multi-Turn Mock Sequences Fast (~5ms) High Agentic workflows and local tool-calling loops
6. Deterministic Markdown Snapshots Instant (<1ms) Low Markdown parsers, code block highlighters, and custom UI formatting
7. Live Contract Testing Slow (sec/min) Low Nightly CI verification of real LLM schemas and SDK compatibility

Final Architectural Observation

Testing AI-powered Vue components does not mean you have to sacrifice the speed, reliability, and cost-efficiency of your test suite.

By pushing the LLM boundary to the edges of your architecture—through MSW network interception, composable dependency injection, or Pinia state seeding—you transform non-deterministic external calls into predictable, isolated unit tests. Save the live API calls for dedicated contract tests, and keep your everyday development workflow fast, deterministic, and offline.

Post a Comment

Previous Post Next Post