The user wants a "micro-frontend resilience test" that covers three specific scenarios:
- Network Partitions: Cutting off communication between micro-frontends or between a micro-frontend and its backend services.
- Version Skew: Running different versions of micro-frontends or shared libraries simultaneously (simulating a rolling update or mismatch).
- Shared Dependency Outages: Simulating a failure in a common library, utility, or shared state container that other micro-frontends rely on.
The request implies a need for a concrete artifact. A "test" usually means code or a configuration script. Since micro-frontends can be implemented in various ways (Module Federation, Single-SPA, iframe based, etc.), a purely code-based test might be too specific. However, a Chaos Engineering experiment using a tool like Gremlin or Chaos Mesh is often the standard for "resilience testing" infrastructure.
Alternatively, I can provide a test plan accompanied by implementation scripts (e.g., using Playwright/Cypress for E2E simulation and toxiproxy/pumba for network chaos).
Let's aim for a comprehensive solution that mixes E2E Testing (Cypress/Playwright) (for functional verification) with Chaos Engineering scripts (for injecting the faults).
Target Audience/Context: Developers or QA engineers working on a distributed frontend system. They likely need something actionable.
Plan of Action:
- Define the Architecture: Assume a host app and two remote micro-frontends (MFE-A, MFE-B) sharing a common dependency (e.g., a Design System or Auth Module).
- Tool Selection:
- Network Partition:
toxiproxy (client-side or gateway) or simple browser developer tools tricks via automation (Cypress). Let's go with Cypress because it's accessible and allows mocking network failure at the browser level, which is relevant for client-side micro-frontends.
- Version Skew: This is hard to do "live" in a single browser session without redeploying. I will simulate this by mocking the manifest or the entry point of one MFE to load a different URL (representing a different version).
- Shared Dependency Outage: Mock the shared module to throw an error or fail to load.
- Drafting the Test Code (Cypress):
- Cypress is a great vehicle for this because it allows interception of network requests and dynamic modification of the DOM/JS environment.
Scenario 1: Network Partition (The "Silent" MFE)
- Goal: Verify the Host App handles MFE-B failing to load gracefully (e.g., showing an error boundary or fallback UI).
- Method:
cy.intercept('GET', '**/mfe-b.js', { forceNetworkError: true }).
Scenario 2: Version Skew (The "Confused" State)
- Goal: Verify that MFE-A (v2) can interact with the Host (v1) or MFE-B (v1) without crashing, or at least degrades functionally.
- Method: Serve a "v2" entry point for MFE-A. The "v2" script might expect a global function that doesn't exist. We need to verify error boundaries or graceful degradation.
Scenario 3: Shared Dependency Outage (The "Broken Foundation")
- Goal: If the "DesignSystem" library fails, do all MFEs crash, or do they have local fallbacks?
- Method: Intercept the request for the shared chunk and return 500 or 404.
Structuring the Response:
- Introduction: Briefly explain the philosophy (Defensive Programming).
- The Test Suite (Cypress): Provide a single, copy-pasteable test file that demonstrates all three scenarios.
- Breakdown: Explain why each test matters and what specific code patterns (Error Boundaries, Semantic Versioning checks) are being tested.
- Infrastructure/Container Level (Bonus): Mention how to do this at the infrastructure level (e.g., using Toxiproxy or Service Mesh) for completeness, acknowledging that browser-side is just one layer.
Refining the Code Snippet:
I will write a Cypress test suite.
- Setup:
beforeEach visits the host.
- Test 1 (Network): Block MFE-1.
- Test 2 (Version Skew): This is tricky in a browser test. A good way to simulate this is to intercept the
remoteEntry.json or specific chunk and serve an older/newer one, or simply manipulate a global variable the MFE depends on to simulate an API contract break. Let's go with simulating a contract break: intercept an API call from the MFE and return a shape it doesn't expect, or mock a shared global state object to be missing.
- Test 3 (Shared Dep): Block
common-utils.js.
Let's refine "Version Skew". In Module Federation, version skew happens when the Host expects v1 of a shared lib, but a Remote brings v2, or vice versa.
- Simulation: Intercept the request for the shared library (e.g., React or a custom lib) from a specific MFE and serve a different/broken version, or serve a manifest pointing to a different entry.
Let's stick to a pragmatic approach using Cypress cy.intercept. It is the most direct way to "inject" these faults for a frontend developer.
Drafting the content:
- Title: Micro-Frontend Chaos Engineering Suite.
- Prerequisites: Cypress installed.
- The Code:
describe('Micro-Frontend Resilience Tests', ...)
- Context: Network Partition ->
cy.intercept returns 503 or drops connection.
- Context: Version Skew ->
cy.intercept serves a "vNext" manifest which might be incompatible, or mocking a shared global interface to be undefined.
- Context: Shared Dependency Outage ->
cy.intercept for shared chunk returns 500.
Self-Correction during drafting:
Just showing code is dry. I should frame it as a "Chaos Experiment" methodology.
I will provide a Cypress test file, as it's the most standard tool for E2E logic, but I will explain that for infrastructure resilience (e.g., the browser can't even reach the server), tools like Toxiproxy are better. However, the user asked to compose a test, implying code I can give them. Cypress is executable.
Detailed Scenario Logic:
Final Polish:
I will organize the response into:
- The Strategy: What we are testing.
- The Test Suite (Code): A Cypress implementation.
- The Checklist: What to look for in the results.
Let's write the Cypress code mentally first to ensure it looks good.
cy.intercept('GET', '**/mfe-recommendations.js', { forceNetworkError: true }).as('partition');
// ... asserts ...
cy.intercept('GET', '**/api/v1/products', { fixture: 'products-v2.json' }).as('skew');
// ... asserts that MFE handles bad data ...
cy.intercept('GET', '**/node_modules/shared-utils.js', { statusCode: 500 }).as('depOutage');
// ... asserts that fallbacks trigger ...
This looks solid. I will present this clearly. I will also add a "Infrastructure/DevOps" section for doing this at the Kubernetes/Docker level for completeness, as "Network Partition" is often a lower-level concern than the browser.
The user asked to compose a test. I will provide a robust Cypress Spec file.
Constructing the "Version Skew" Injection:
How to inject version skew dynamically?
Option A: Point the remote entry URL to a different environment (e.g., staging vs prod).
Option B: Mock the specific behavior of the new version.
I will use Option A as a conceptual approach in the comments, but for the executable code, I will simulate the effect of skew: API incompatibility.
Let's start writing.
This is a comprehensive resilience testing suite designed for a Micro-Frontend (MFE) architecture. It uses Cypress as the automation driver because it allows for precise interception of network requests and manipulation of the browser environment, which is essential for simulating these specific failure modes.
The Strategy
To ensure your MFE shell (Host) and remote fragments (Remotes) are resilient, we must answer three questions:
- Network Partition: Can the shell survive if a specific remote's assets (JS/CSS) fail to load?
- Shared Dependency Outage: If a shared library (like React or a Design System) fails, do remotes crash the entire app or fail gracefully?
- Version Skew: If the Host expects
v1 of a contract but the Remote serves v2 (or incompatible data), does the UI break or handle the exception?
The Test Suite
Save this file as cypress/e2e/mfe-resilience.cy.js.
describe('Micro-Frontend Chaos Engineering', () => {
const MFE_ENDPOINTS = {
recommendations: '/assets/remoteRecommendations.js',
sharedDesignSystem: '/assets/shared-design-system.min.js',
userProfile: '/api/user-profile', // API backing an MFE
};
/**
* SCENARIO 1: NETWORK PARTITION
* Simulate a complete loss of connectivity to a specific MFE remote.
* Expected Behavior: The Shell should render an Error Boundary or Fallback UI.
* The rest of the application must remain interactive.
*/
context('Network Partitions', () => {
it('Should render a fallback UI when a Remote MFE fails to load (503)', () => {
// Intercept the request for the specific MFE script and force a failure
cy.intercept('GET', MFE_ENDPOINTS.recommendations, {
statusCode: 503,
body: 'Service Unavailable',
}).as('getRecommendationsFail');
cy.visit('/dashboard');
// Wait for the failed attempt
cy.wait('@getRecommendationsFail');
// ASSERT: The specific MFE slot shows a graceful error
cy.get('[data-cy="recommendations-slot"]')
.should('contain', 'Failed to load recommendations')
.and('be.visible');
// ASSERT: The Host Shell is NOT broken (Global crash check)
cy.get('#main-header').should('be.visible');
cy.get('[data-cy="critical-feature"]').should('work');
});
it('Should handle client-side timeouts gracefully', () => {
// Simulate a hanging request that never resolves
cy.intercept('GET', MFE_ENDPOINTS.recommendations, (req) => {
req.reply(() => {
// Never call reply() -> forces timeout
return new Promise(() => {});
});
}).as('getRecommendationsTimeout');
cy.visit('/dashboard', { timeout: 10000 }); // Lower timeout for test speed
// ASSERT: Eventually a timeout fallback appears
cy.get('[data-cy="recommendations-slot"]', { timeout: 15000 })
.should('contain', 'Request timed out');
});
});
/**
* SCENARIO 2: SHARED DEPENDENCY OUTAGE
* Simulate a failure in a shared utility (e.g., a design system or auth library)
* loaded via Module Federation.
* Expected Behavior: Error Boundaries should catch the import error.
*/
context('Shared Dependency Outages', () => {
it('Should isolate failures when a shared library script errors', () => {
// Intercept the shared library and return garbage JS to trigger a SyntaxError
cy.intercept('GET', MFE_ENDPOINTS.sharedDesignSystem, {
statusCode: 200,
body: 'this is not valid javascript !!!',
headers: { 'Content-Type': 'application/javascript' },
}).as('corruptDependency');
cy.visit('/dashboard');
// ASSERT: The global error boundary catches the syntax error
cy.get('[data-cy="global-error-boundary"]')
.should('exist')
.and('contain', 'Something went wrong');
// ASSERT: Ensure the error was reported to monitoring (mocked check)
cy.window().then((win) => {
expect(win.__ERROR_REPORTED__).to.be.true;
});
});
});
/**
* SCENARIO 3: VERSION SKEW (CONTRACT MISMATCH)
* Simulate a scenario where the Host expects data format A, but the Remote
* (or its backing API) returns format B. This tests logical resilience.
*/
context('Version Skew & Contract Violations', () => {
it('Should handle mismatched API schemas without crashing', () => {
// The Host expects: { user: { name: 'John' } }
// The Remote API returns a new schema: { identity: { firstName: 'John' } }
cy.intercept('GET', MFE_ENDPOINTS.userProfile, {
statusCode: 200,
body: {
identity: {
firstName: 'John',
lastName: 'Doe',
},
// Missing 'user' object
},
}).as('skewedData');
cy.visit('/profile');
// ASSERT: The component attempts to render but handles undefined gracefully
// It should NOT render "undefined" or crash the page
cy.get('[data-cy="profile-welcome"]')
.invoke('text')
.should('not.match', /undefined|null/);
// Ideally, it shows a generic fallback
cy.get('[data-cy="profile-welcome"]').should('contain', 'Welcome User');
});
it('Should survive if a Remote exposes an incompatible component interface', () => {
// Simulate a remote that loads but exposes a method that throws immediately
cy.intercept('GET', MFE_ENDPOINTS.recommendations, (req) => {
req.continue((res) => {
// We inject a script that overwrites the expected export with a throwing function
const maliciousCode = `
window.recommendationsComponent = {
mount: () => { throw new Error("Incompatible Version: mount() signature changed"); }
};
`;
res.body = res.body + "\n" + maliciousCode;
});
}).as('skewedVersion');
cy.visit('/dashboard');
// ASSERT: The Error Boundary for that specific MFE catches the runtime error
cy.get('[data-cy="recommendations-error-boundary"]')
.should('contain', 'Update Required');
});
});
});
Implementation Checklist
To make these tests pass, your Micro-Frontend architecture requires specific resilience patterns:
- Error Boundaries: Every MFE slot in the Host application must be wrapped in an Error Boundary (React) or a
try/catch wrapper (Vue/Angular).
- Why: To prevent a crash in
Recommendations from unmounting the Header or Checkout.
- CSS Isolation: Ensure that if an MFE CSS file fails (403/404), it does not break the layout of the host.
- Defensive Programming:
- Null Checks: Always
user?.name instead of user.name to handle version skew in data contracts.
- Schema Validation: Validate API responses before rendering.
- Loading States: Ensure the UI handles delays (Scenario 1.2) without "jumping" layout shifts (CLS).
Infrastructure Level (Optional)
If you are running this in a CI/CD pipeline, you can inject these faults at the Docker/Kubernetes level using Chaos Mesh or Toxiproxy:
- Network Partition: Configure the ingress to drop packets to
service-b specifically for the test runner's IP.
- Latency: Add 5s latency to the database connection used by the MFE to test frontend skeleton loading states.