Skip to content

Angular MFE local testing: shell and remotes together

You will run the OrdersPortal shell and the orders-mfe remote together on one machine, check the federation wiring with plain HTTP requests, unit-test the shell’s fallback behavior with Vitest, serve production builds locally to catch problems the dev server hides, and rehearse a remote outage and a remote deployment under an open tab. The page also lists the errors you are most likely to see and what each one means.

How to run the samples: run commands from the workspace root. The Node.js script in Step 5 is an ES module; save it as serve.mjs and run it with Node.js 22 or later. All commands and tests on this page were run with Angular CLI 22.2.7, Vitest 5.1 and Node.js 22.23; browser checks used headless Chrome driven by Playwright.

Level Question it answers Where it runs
Unit Does this component, service or route function behave? Inside one app, no federation involved
Shell routing Does the shell mount the remote and fall back when it fails? Shell unit tests with a fake loader
Remote standalone Does the remote work on its own routes? Remote dev server or build
Composition Do shell and remote work together with shared dependencies? Both apps running locally
Production-like Do the built artifacts load across origins with real caching and fallbacks? Static servers over dist/, then a deployed preview environment
End-to-end Do user journeys work across all deployed apps? Browser automation against a deployed environment

The federation-specific risks (wrong URLs, CORS, version negotiation, a missing remote) only appear from the composition level up, so do not stop at unit tests.

Open two terminals:

Terminal window
npx ng serve orders-mfe # http://localhost:4201
Terminal window
npx ng serve orders-portal # http://localhost:4200

Start the remote first. The ports come from the serve-original targets that the federation schematic wrote into angular.json. If you change a port, change the matching URL in federation.manifest.json as well.

Verify: both terminals end with “Watch mode enabled. Watching for file changes…” and a Local: URL.

Step 2: Check the wiring with HTTP requests

Section titled “Step 2: Check the wiring with HTTP requests”

Before opening a browser, confirm each federation file is served:

Terminal window
curl -s http://localhost:4200/federation.manifest.json
curl -s http://localhost:4201/remoteEntry.json | head -3
curl -s -D - -o /dev/null -H "Origin: http://localhost:4200" http://localhost:4201/remoteEntry.json

Expected results:

{
"orders-mfe": "http://localhost:4201/remoteEntry.json"
}
{
"$version": "v4",
"name": "orders-mfe",
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
...

The third request shows that the dev server already sends a permissive CORS header, which is why cross-port loading works locally. Production hosting will not do this for you; see Azure deployment.

Verify: open http://localhost:4200/orders in a browser. The order list renders inside the shell. In the Network panel, filter by remoteEntry and routes: the remote’s route chunk is requested only on first navigation to /orders.

ng test uses the @angular/build:unit-test builder, which expects an application build target. After the federation schematic, the default build target is the federation builder, and ng test warns:

The 'buildTarget' is configured to use '@angular-architects/native-federation:build', which is not supported.

Unit tests do not need federation. Point the test target at the plain esbuild target in angular.json:

"test": {
"builder": "@angular/build:unit-test",
"options": {
"buildTarget": "orders-portal:esbuild:development"
}
}

Do the same for orders-mfe. Verify: npx ng test orders-portal --watch=false runs without the warning.

Because the shell’s routes are built from a loader function, you can test the failure path without any network or federation runtime:

src/app/app.routes.spec.ts
import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { createRoutes } from './app.routes';
import { RemoteUnavailable } from './remote-unavailable';
describe('shell routes', () => {
it('renders the fallback when orders-mfe cannot be loaded', async () => {
const failingLoader = () => Promise.reject(new Error('remoteEntry.json: 404'));
TestBed.configureTestingModule({
providers: [provideRouter(createRoutes(failingLoader as never))],
});
const harness = await RouterTestingHarness.create();
const component = await harness.navigateByUrl('/orders', RemoteUnavailable);
expect(component).toBeInstanceOf(RemoteUnavailable);
expect(TestBed.inject(Router).url).toBe('/orders');
});
});

Run only this file (a workspace-relative --include path works):

Terminal window
npx ng test orders-portal --watch=false --include=projects/orders-portal/src/app/app.routes.spec.ts
Test Files 1 passed (1)
Tests 1 passed (1)

Without --include, the run also picks up app.spec.ts from Host application setup and reports Test Files 2 passed (2).

Add a second test with a loader that resolves { ORDERS_ROUTES: [...] } containing a stub component to prove the happy path mounts the routes under /orders.

Test the remote’s pages the usual way, inside the remote project: they are ordinary standalone components and routes.

The dev server is forgiving: it sends CORS headers, never caches, and serves index.html for unknown paths. Production hosting differs on all three. Build both apps and serve them with a tiny static server that behaves more like real hosting:

Terminal window
npx ng build orders-mfe
npx ng build orders-portal
// serve.mjs: static server with SPA fallback and an explicit CORS origin
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
const [root, port, allowOrigin] = [process.argv[2], Number(process.argv[3]), process.argv[4]];
const types = { '.js': 'text/javascript', '.json': 'application/json', '.html': 'text/html', '.css': 'text/css' };
http
.createServer((req, res) => {
const urlPath = decodeURIComponent(req.url.split('?')[0]);
let file = path.join(root, urlPath);
const exists = fs.existsSync(file) && fs.statSync(file).isFile();
if (allowOrigin) res.setHeader('Access-Control-Allow-Origin', allowOrigin);
// Only extensionless paths fall back to index.html; missing .js/.json files must 404.
if (!exists && path.extname(urlPath) === '') file = path.join(root, 'index.html');
else if (!exists) return res.writeHead(404).end();
res.setHeader('Content-Type', types[path.extname(file)] ?? 'application/octet-stream');
fs.createReadStream(file).pipe(res);
})
.listen(port, () => console.log(`Serving ${root} on http://localhost:${port}`));
Terminal window
node serve.mjs dist/orders-mfe/browser 4201 http://localhost:4200
node serve.mjs dist/orders-portal/browser 4200

Output:

Serving dist/orders-mfe/browser on http://localhost:4201
Serving dist/orders-portal/browser on http://localhost:4200

Open http://localhost:4200/orders/ord-1002: the shell renders “Order ord-1002” from the production build of the remote. Now try two deliberate mistakes to see what production failures look like:

  • Start the remote server without the third argument (no CORS header). The shell shows the fallback, and the console reports the real cause first:

    Access to fetch at 'http://localhost:4201/remoteEntry.json' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    [NF][6]: Failed to load module orders-mfe/./routes: {error: NFError: Remote 'orders-mfe' is not initialized.
    orders-mfe failed to load NFError: Failed to load module orders-mfe/./routes
  • Serve the remote from a folder that answers every path with index.html (a careless SPA fallback). The missing metadata now comes back as HTML with status 200 instead of a 404, and the console shows only the generic NFError: Failed to load module orders-mfe/./routes, with no hint that the file was HTML. This is exactly the misconfiguration to avoid when you set up SPA fallbacks in production, because it hides the real cause.

Build both apps immediately before serving them. ng serve writes development artifacts (files ending in -dev.js) into the same dist/<project>/browser folder. If you run ng serve orders-mfe and then serve dist/ next to a production shell build, the shared bundles no longer match and the shell fails with ReferenceError: ngDevMode is not defined. A fresh ng build fixes it.

For headless checks in CI, a Chromium-based browser can print the rendered DOM:

Terminal window
google-chrome --headless=new --virtual-time-budget=8000 --dump-dom http://localhost:4200/orders | grep -o '<main>.*</main>'

With both production servers running, stop the remote’s server and reload http://localhost:4200/orders. Expected result:

<main><router-outlet></router-outlet><app-remote-unavailable><p role="alert">This area is temporarily unavailable.</p><button type="button">Reload the page</button></app-remote-unavailable><!----></main>

The shell’s header and other routes keep working. With @angular-architects/native-federation 22.2.5 the shell still bootstrapped when the remote was unreachable at startup, and the failure appeared only when the /orders route loaded. Rehearse this on every upgrade of the federation package, because startup behavior on missing remotes is a runtime implementation detail.

Step 7: Rehearse a deployment under an open tab

Section titled “Step 7: Rehearse a deployment under an open tab”

A real deployment replaces the remote’s files while users have the shell open. Rehearse it with two builds of the remote and the static server:

  1. Build the remote, copy dist/orders-mfe/browser to release-1, and serve a copy of it as site-mfe on port 4201 (node serve.mjs site-mfe 4201 http://localhost:4200).
  2. Change something visible in the remote (for example a line in order-detail.ts), build again and copy the output to release-2. The remote’s own files get new hashes (order-detail-G5LQHHY2.js became order-detail-5S4JTHJA.js); the shared Angular bundles keep theirs.
  3. Open http://localhost:4200/orders in the browser and leave the tab open.
  4. “Deploy”: delete everything in site-mfe and copy release-2 into it, as a full-replacement host such as Azure Static Web Apps does.
  5. In the open tab, click ord-1002.

Without the shell’s reloadOnStaleChunk handler, the click did nothing visible, and the console showed:

[http 404] /order-detail-G5LQHHY2.js
ERROR TypeError: 404 Not Found http://localhost:4201/order-detail-G5LQHHY2.js

With the handler from Host application setup, the same click logged the same error, reloaded once, and rendered the new release’s detail page at /orders/ord-1002. Repeating the deployment with release-1’s .js files copied into site-mfe first (the carry-forward step from Azure deployment) produced no error at all: the click rendered the old detail page and the next reload showed the new one.

The same setup rehearses version skew: serve a remote built with another Angular minor and watch the area stay empty with NG0203 in the console. Advanced concepts shows that run.

Step 8: End-to-end tests against a deployed environment

Section titled “Step 8: End-to-end tests against a deployed environment”

Run browser end-to-end tests (for example Playwright or Cypress) against a deployed preview environment where the shell’s manifest points at the remote builds under test, not against local dev servers. The following Playwright test is a fragment that was not run for this page; adapt the URL to your preview environment:

e2e/orders.spec.ts
import { test, expect } from '@playwright/test';
test('orders area loads from the remote', async ({ page }) => {
await page.goto('https://portal-preview.example.test/orders');
await expect(page.getByRole('heading', { name: 'Orders' })).toBeVisible();
});

Contract tests belong first in the remote’s pipeline, where the breaking change is made: the remote’s build is checked against the shell’s expectations before it is deployed. The shell’s pipeline runs the same script against deployed URLs as a smoke test after changing an environment’s manifest. The script and its real output are in Azure deployment.

  • “Port 4200 is already in use”. A previous ng serve or static server is still running. Stop it; on macOS or Linux, lsof -i :4200 shows the process.
  • CORS error for remoteEntry.json in the console. The remote’s server does not send Access-Control-Allow-Origin for the shell’s origin. Locally this means you are not using ng serve or the serve.mjs origin argument.
  • NFError: Failed to load module orders-mfe/./routes with no network error. Open the remoteEntry.json URL directly. If it returns your index.html, a SPA fallback is masking a missing file; fix the URL and exclude .json and .js from fallbacks.
  • ReferenceError: ngDevMode is not defined when serving built files. Development artifacts from ng serve were mixed with a production build in dist/. Run ng build for every app again before serving.
  • Two _angular_core files load from different origins and the remote’s area stays empty with NG0203. Shell and remote were built against different Angular minors. Align them and rebuild, and add the contract check to the remote’s pipeline.
  • A click inside the remote does nothing after you rebuilt it, and the console shows TypeError: 404 Not Found ...-<hash>.js. The open tab still uses the previous remoteEntry.json. Reload, and see Step 7 for the production fix.
  • Changes in the remote do not appear in the shell. The browser cached the remote’s metadata or chunks. Use a hard reload, or disable the cache in developer tools while testing.
  • ng test warns about the federation builder. Apply Step 3.

Deploy both apps in Azure deployment, or read Advanced concepts for versioning and error-handling strategies.