QA
Intermediate LevelVue JS

How do you mock API network requests in Vitest/Vue Test Utils using Mock Service Worker (MSW)?

❓ Interview Prompt: Explain component testing API mocking, Mock Service Worker (MSW) network interception, and testing composable fetch workflows.

Instead of manually mocking 'global.fetch' or Axios in every test file, Mock Service Worker (MSW) intercepts network requests at the network layer using Service Workers (or Node request interceptors).

Advantages:

Your Vue components and composables run their real network code during unit tests. MSW returns mock JSON payloads seamlessly without altering application source code!

Code Implementation Example

javascript
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
import { mount } from '@vue/test-utils';

// Setup MSW mock API handler
const server = setupServer(
  http.get('/api/user', () => HttpResponse.json({ name: 'Alice' }))
);

beforeAll(() => server.listen());
afterAll(() => server.close());

test('fetches and displays user name', async () => {
  const wrapper = mount(UserFetcher);
  await new Promise(r => setTimeout(r, 100)); // Wait for MSW fetch
  expect(wrapper.text()).toContain('Alice');
});
💡Intercepting network API calls in Vue component tests using MSW.
🎯 Interview Key Takeaway

Use Mock Service Worker (MSW) to intercept network requests at the network level during Vitest component tests.

#MSW#Testing#Vitest#Intermediate
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?