都市固體廢棄物的美麗
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中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

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

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。
