DEV Community

Cover image for Mastering API Testing with Mocking in TypeScript: An Intro to Mock Service Worker
Dylan Britz
Dylan Britz

Posted on • Edited on • Originally published at dylanbritz.dev

3 1 1 1

Mastering API Testing with Mocking in TypeScript: An Intro to Mock Service Worker

Hey fellow developers! 👋 If you’re diving into the front-end world and struggling with API testing, you’re about to discover your new best friend: Mock Service Worker (MSW). Trust me, this library is a game-changer for TypeScript projects!

What’s the Deal with API Mocking ?

When building front-end applications, we’re constantly hitting APIs — but what happens when those APIs aren’t ready? Or when you need to test error states? That’s where mocking comes in!

Mock Service Worker stands out from traditional mocking solutions by intercepting actual network requests right at the browser or Node.js level. No more complicated setup or maintaining separate mock servers!

Why MSW Will Make Your Life Easier

Here’s why you should be excited about MSW:

  • Works seamlessly in any environment - browser, Node.js, or testing frameworks
  • Intercepts actual network requests giving you realistic testing scenarios
  • Plays perfectly with TypeScript
  • Reuse the same mocks everywhere

Getting Started with MSW

Let’s set up MSW in your project with these simple steps:

  1. Install the package
npm install msw --save-dev
Enter fullscreen mode Exit fullscreen mode
  1. Create your mock handlers First, make a directory for your mocks:
mkdir src/mocks
touch src/mocks/handlers.ts
Enter fullscreen mode Exit fullscreen mode

Then define your API mocks in the handlers file:

import { rest } from 'msw';

export const handlers = [
  rest.get('/api/user', (req, res, ctx) => {
    return res(
      ctx.status(200),
      ctx.json({
        id: 1,
        username: 'john_doe',
        email: 'john@example.com',
      })
    );
  }),
];
Enter fullscreen mode Exit fullscreen mode
  1. Set up the service worker Create a browser setup file:
// src/mocks/browser.ts
import { setupWorker } from 'msw';
import { handlers } from './handlers';

export const worker = setupWorker(...handlers);
Then activate it in your apps entry point:

// src/index.tsx
if (process.env.NODE_ENV === 'development') {
  const { worker } = require('./mocks/browser');
  worker.start();
}
Enter fullscreen mode Exit fullscreen mode
  1. For testing environments If you’re using Jest or another testing framework:
// src/mocks/server.ts
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);
Enter fullscreen mode Exit fullscreen mode

In your test setup:

// setupTests.ts
import { server } from './mocks/server';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Enter fullscreen mode Exit fullscreen mode

Level Up Your Mocking Game with TypeScript

One of the coolest things about MSW is how it leverages TypeScript’s power. Check this out:

import { rest } from 'msw';
import { User } from './types'; // Your User interface

export const handlers = [
  rest.get<{}, {}, User>('/api/user', (req, res, ctx) => {
    return res(
      ctx.json({
        id: 2,
        username: 'jane_doe',
        email: 'jane@example.com',
      })
    );
  }),
];
Enter fullscreen mode Exit fullscreen mode

Now your mocks are type-checked against your actual interfaces! No more mismatched data structures causing bugs at runtime.

Pro Tips for MSW Success

Here are some tips I’ve learned from using MSW in production:

Mock different response states — Success, errors, loading states — test them all!

// Error state mock 
rest.get('/api/users', (req, res, ctx) => {
  return res(
    ctx.status(500),
    ctx.json({ message: 'Internal server error' })
  );
})
Enter fullscreen mode Exit fullscreen mode
  • Organize your mocks by feature and Keep related endpoints together for better maintainability
  • Combine MSW with Storybook to create component stories with realistic data flows
  • Empty arrays, weird data formats, network timeouts — simulate it all!
  • Keep your mocks close to your real API. The more realistic your mocks, the more valuable your tests

MSW vs. Traditional Mocking: Why MSW Wins

I’ve tried many mocking solutions, and here’s why MSW stands out:

Traditional Mocking Mock Service Worker
Complex setup with local servers Simple configuration
Limited to specific environments Works everywhere
Mocks often feel disconnected from reality Simulates actual network behavior
Requires different approaches for different contexts Reuse mocks across all environments
Often lacks TypeScript integration Fully type-safe

No more flaky API calls!

Implementing MSW in your TypeScript projects will change how you approach development and testing. You’ll build more robust applications, catch bugs earlier, and spend less time wrestling with backend dependencies.

Start small mock just one endpoint and see the difference it makes in your workflow. Then gradually expand your mocks as you get comfortable with the approach.

Have you tried MSW or other mocking solutions? What challenges are you facing with API testing? Drop your thoughts in the comments, and let’s discuss.

Happy coding! 🚀

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (6)

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

This is a very cool library, especially useful inside tests. Thanks for sharing 😀

Collapse
 
nevodavid profile image
Nevo David

This is really neat and very clear, helpful for learning!

Collapse
 
bugnificent profile image
Yusuf Aşık

Is there any security concern you experienced? I will give it a try if not!

Collapse
 
britzdm profile image
Dylan Britz

What do you mean exactly by security concern?

Collapse
 
bugnificent profile image
Yusuf Aşık • Edited

I heard its working on browser-side, so we may miss CSRF/XSS protection, simulating TLS/Firewall behaviour or API Gateway Logic.

Thread Thread
 
britzdm profile image
Dylan Britz

this is simply to mock API request to third party API's, or your own on the front end.

I think you will need to mock those in your front end only if it affects it. Otherwise leave it to the backend

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay