Checking UI Behavior During API Failures Without Touching Production Using Mock Service Worker

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About This Article
This article was created using an automated generation workflow leveraging generative AI. Official documentation and fixed educational material implementations were reviewed to organize operational and technical constraints.

Verification Status: 📘 Official Information and Implementation Cross-Checked. Actual browser testing not performed.

Verify UI prompts corresponding to API responses without a production connection. First, simulate normal responses, access denials, and temporary unavailability using standard browser Response objects, and distinguish them from MSW when additional settings are required.

Open Live Demo

Key Terms to Know First

  • MockA process that returns predefined responses instead of actual ones.

  • HTTP StatusA numerical code representing the response result.

Understanding via Process Flowchart

Read from left to right. Anticipate how changes in "mock responses" affect "user guidance".

flowchart LR
    A["画面のリクエスト"] --> B["擬似応答"] --> C["利用者への案内"]

Live Demo Operations

Select 200, 403, and 503 in sequence. Observe the differences in guidance.

How to Read the Results

Display simulated responses for success, access denial, and temporary unavailability separately.

In this educational material, 403 is mapped to permission verification guidance, and 503 is mapped to retry timing guidance. Grouping them simply as "errors" makes it difficult for users to choose their next action.

Key Code Points

Create a standard browser Response from the corresponding response and test the guidance branching. When using MSW, keep the guidance branching logic intact and replace the mock response section with a handler.

The implementation can be checked in the Implementation Code of the demo screen. When returning the same response with MSW,http.get specify the validation URL in .

import { http, HttpResponse } from 'msw';

const handlers = [
  http.get('/demo-api/items', () =>
    HttpResponse.json({ message: '時間をおいて試してください。' }, { status: 503 })
  ),
];

When using it in a browser, deploy the MSW Service Worker to the staging environment. Refer to README for detailed setup instructions.

When using in production

Verify error guidance and retry paths before connecting to the actual environment.

Compare by first using a method that does not perform network communication.

The initial input is 503. Clicking the execute button is expected to output the method, status, and result. Next, change it to 200 and execute, and finally specify 403. For 200, dummy documents A and B are returned as an array; for 403, guidance checking access permissions is returned; and for 503, guidance to try again later is returned. Note that the JSON structure received by the screen differs between success and error cases.

Specified stateMeaning of expected result
200Receive the list of documents
403Example indicating that the request was rejected
503Example guidance for temporary service unavailability

A 403 generally indicates that the request was understood but refused, and it is not necessarily caused solely by insufficient user permissions. Similarly, a 503 has multiple causes such as overload or maintenance, and there is no guarantee that service will definitely recover after a certain period. The display message is for this mock scenario. In an actual service, determine the guidance based on the information returned by the server and operational policies.

Processing tested in the default demo

The implementation checks whether the specified numeric value is one of 200, 403, or 503, and constructs a Response object from the corresponding payload using Response.json. It then passes this to the display function, outputting the status and JSON contents to the results section. There is no actual requirement for the server to stop or for network communication to occur. When executing the same response generation in Node.js this time, the status and body matched for all three types, and response.ok was true only for 200. This confirms the response generation logic of the default demo and is not a test of MSW network interception.

In production communication via fetch, it is necessary to distinguish between receiving an HTTP error response and failing communication itself, which results in an exception. Merely receiving a response other than 200 does not necessarily cause a JavaScript exception. Timeouts, non-JSON responses, and re-acquiring authentication should be handled as separate verification cases.

When adding and trying MSW

MSW is a mechanism that prepares handlers corresponding to network requests and returns test responses. This learning material includes a button to test with MSW after setup. Clicking it verifies the retrieval of mockServiceWorker.js in the same directory, and if not ready, displays guidance to refer to the README. If ready, it loads msw and msw/browser, and registers a GET handler corresponding to the relative URL for the demo. There is processing to start the worker, execute the fetch, and stop it in the finally block.

Unlike the generation of standard Responses, this additional operation involves retrieving the worker file and actual communication processing. We have not confirmed that workers are available on the current public Pages. In accordance with the README, configure this only in an authorized test distribution environment. Check the target URL and the Service Worker scope, and do not direct it to production services. Note also that since onUnhandledRequest in the implementation is set to bypass, it is not a mechanism to block communications that do not match any handler.

Applying to screen error handling

If the API and UI development teams are separate, sharing the response contract and typical error cases in advance allows you to consider guidance and retries before connecting to production. For cases where permissions are denied, consider guiding the user on necessary operational privileges, and for cases where the service is temporarily unavailable, consider recovery information and retry conditions. Rather than increasing the number of automatic retries indefinitely, verify whether the target operation can be safely retransmitted.

If the initial demo is normal but only the MSW addition operation fails, check the existence of the worker file, distribution conditions such as HTTPS, the scope, and the handler URL. Use only fictitious data names, and do not input actual authentication tokens or internal API information into public learning materials. Do not confuse the ability of the simulated environment to handle screens with the recovery of production failures.

Verification Scope

Material targets: Standard Response API / MSW 2.7.0 (when additionally configured). Executed Response.json(payload, {status}) identical to the implementation on Node.js v22.16.0 for 200/403/503. Status and JSON matched for all cases; ok was true/false/false. MSW itself, worker deployment, and browser communication were not executed. Retrieval of external CDNs, fixed-version licenses with actual browser rendering, and Mermaid diagram rendering remain unconfirmed.

Reference Materials

GitHub Sample

Implementation and Experiment Procedure

Document information

Article title
Checking UI Behavior During API Failures Without Touching Production Using Mock Service Worker
Published
Updated
Source
https://papanda925.com/?p=19130&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL