搜尋
首頁web前端js教程都市固體廢棄物的美麗

The beauty of MSW

Why We Love MSW

Back in the day, when we were trying to create a new project, we considered the possibility of not depending heavily on the backend. Our idea was to receive mocks for the backend's current work and then proceed in parallel. This approach would allow us to have the necessary data ready when the backend completed its work, so we wouldn't need to make any changes. Once the backend was deployed, we could simply disable the mocks in the development server and switch to the real endpoints.

I'm sure many tools exist that enable you to create mocks and replace them later with real endpoints. However, we found a great solution: Mock Service Worker (MSW).

What is MSW?

MSW is a powerful tool that allows you to intercept and mock network requests. It works both on the client-side and server-side, making it incredibly versatile. With MSW, you can create realistic mocks for your API endpoints, enabling you to develop and test your application without relying on the actual backend.

Benefits of Using MSW

Local Development

MSW helps to avoid making numerous calls to the backend during local development. This reduces load on the backend services and speeds up the development process. Here's an example of how you can set up MSW for local development:

// src/mocks/handlers.js
import { rest } from 'msw';

export const handlers =
  [
    http.get(
      URL,
      ({
        request,
      }) => {
        return HttpResponse.json(
          {
            title:
              'Mock Data',
          },
        );
      },
    ),
  ];
// src/mocks/browser.js
import { setupWorker } from 'msw';
import { handlers } from './handlers';

export const worker =
  setupWorker(
    ...handlers,
  );
// src/index.js
if (
  process.env
    .NODE_ENV ===
  'development'
) {
  const {
    worker,
  } = require('./mocks/browser');
  worker.start();
}

QA Testing

MSW helps QA teams test the UI without making actual calls to the backend. This is especially useful when the backend is unstable or under heavy development. QA engineers can work with predefined mock data, ensuring that the frontend works as expected.

Automated Testing

For automated testing, MSW avoids the need to intercept each call manually. With a basic configuration, you can mock responses for various scenarios, making your tests more reliable and easier to write. Here’s an example of setting up MSW in a test environment:

// src/mocks/server.js
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server =
  setupServer(
    ...handlers,
  );
// src/setupTests.js
import { server } from './mocks/server';

beforeAll(() =>
  server.listen(),
);
afterEach(() =>
  server.resetHandlers(),
);
afterAll(() =>
  server.close(),
);

How to Handle Handlers

You can organize your handlers by grouping them into separate files and combining them as needed. For example:

// src/mocks/handlers.js
import { userHandlers } from './user';
import { productHandlers } from './product';

export const handlers =
  [
    ...userHandlers,
    ...productHandlers,
  ];

Each handler can have multiple scenarios for testing purposes. Here's an example of how to define and use scenarios:

Scenarios in Handlers

A scenario is a predefined set of responses that simulate different conditions, such as success or error states. This allows you to easily switch between different mock responses.

// src/mocks/user.js
import { rest } from 'msw';

const USER_URL =
  'http://pii.dev.localhost:3200/api/v1/userV2/current';

const scenarios = {
  success: [
    http.get(
      URL,
      ({
        request,
      }) => {
        return HttpResponse.json(
          {
            title:
              'Mock Data',
          },
        );
      },
    ),
  ],
  error: [
    http.get(
      USER_URL,
      () => {
        return HttpResponse.json(
          {
            error:
              'Unauthorized',
          },
          {
            status: 401,
          },
        );
      },
    ),
  ],
};

const scenarioName =
  new URLSearchParams(
    window.location.search,
  ).get(
    'scenario',
  ) || 'success';
export const userHandlers =
  scenarios[
    scenarioName
  ] || [];

Explanation of Scenarios

Scenarios allow you to easily test different conditions your application might encounter. By changing the scenario query parameter in the URL, you can simulate different responses without changing the code.

For example, to test the success scenario, you would navigate to:

http://yourapp.localhost/?scenario=success

And for the error scenario:

http://yourapp.localhost/?scenario=error

This approach allows you to dynamically switch between different mock responses, making your development and testing process more flexible and efficient.


By using MSW, we have a seamless way to handle mock data and API responses in both development and testing environments. It allows us to focus on developing features and writing tests without worrying about the backend's availability or stability. With MSW, we can confidently create realistic mock scenarios and ensure our application works correctly before integrating with the real backend.

I'm still discovering how MSW works. If you have any better solutions, please feel free to tell me.

If you want to check the best practices, feel free to check the documentation.

以上是都市固體廢棄物的美麗的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Java vs JavaScript:開發人員的詳細比較Java vs JavaScript:開發人員的詳細比較May 16, 2025 am 12:01 AM

javaandjavascriptaredistinctlanguages:javaisusedforenterpriseandmobileapps,while javascriptifforInteractiveWebpages.1)JavaisComcompoppored,statieldinglationallyTypted,statilly tater astrunsonjvm.2)

JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)