Testing Module Federation with Webpack 5
Module Federation lets you load code from other deployments at runtime. That's powerful and also a testing nightmare if you don't build the right infrastructure from the start. A federated module doesn't exist in your project — it's fetched over the network at runtime. Jest doesn't know about it. Your CI doesn't have access to it. If you don't solve this deliberately, you end up with tests that can only run against live environments.
This post covers the complete approach: setting up Jest for federated modules, mocking remotes reliably, testing dynamic imports, catching version mismatches, and running integration tests against real remotes.
Why Module Federation Breaks Jest by Default
Webpack 5 Module Federation works through a runtime mechanism that Jest doesn't include. When you try to import a federated module in a test:
import Button from 'designSystem/Button'; // federated remoteJest throws: Cannot find module 'designSystem/Button'
There's no node_modules/designSystem — it exists only in the Webpack runtime. You need to either mock it or set up a resolver that handles federated imports.
Setting Up Jest for Module Federation
The first approach is a custom module name mapper. Add this to jest.config.js:
// jest.config.js
module.exports = {
moduleNameMapper: {
// Map federated modules to local mocks
'^designSystem/(.*)$': '<rootDir>/src/__mocks__/designSystem/$1',
'^cartRemote/(.*)$': '<rootDir>/src/__mocks__/cartRemote/$1',
},
// Other config...
};Then create mock implementations:
// src/__mocks__/designSystem/Button.js
const Button = ({ children, onClick, disabled, variant }) => (
<button
onClick={onClick}
disabled={disabled}
data-variant={variant}
data-testid="ds-button"
>
{children}
</button>
);
export default Button;This works for unit tests. The mock is minimal but implements the interface. The test doesn't care about the actual button styling — it cares that the consumer passes props correctly and responds to events.
Using jest-module-federation
For larger projects, maintain mocks manually becomes tedious. The jest-module-federation package provides a plugin approach:
// jest.config.js
const { createJestConfig } = require('jest-module-federation');
module.exports = createJestConfig({
// Your federation config (mirrors webpack.config.js remotes)
remotes: {
designSystem: 'designSystem@http://localhost:3001/remoteEntry.js',
cartRemote: 'cartRemote@http://localhost:3002/remoteEntry.js',
},
// Where to find mock implementations
mockDir: '<rootDir>/src/__federation-mocks__',
// Fall back to real remotes in integration mode
useRealRemotes: process.env.INTEGRATION_TESTS === 'true',
});This automatically maps federated imports to mocks in unit test mode and can switch to real remotes for integration runs.
Mocking Remote Modules in Tests
For test-specific behavior, override the module-level mock:
// CheckoutForm.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import CheckoutForm from './CheckoutForm';
// Override the default mock for this test file
jest.mock('designSystem/Button', () => ({
default: jest.fn(({ children, onClick, disabled }) => (
<button onClick={onClick} disabled={disabled}>
{children}
</button>
))
}), { virtual: true });
jest.mock('designSystem/Input', () => ({
default: jest.fn(({ value, onChange, placeholder }) => (
<input value={value} onChange={onChange} placeholder={placeholder} />
))
}), { virtual: true });
test('submits form with valid data', async () => {
const onSubmit = jest.fn();
render(<CheckoutForm onSubmit={onSubmit} />);
fireEvent.change(screen.getByPlaceholderText('Email'), {
target: { value: 'alice@example.com' }
});
fireEvent.click(screen.getByText('Place Order'));
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({ email: 'alice@example.com' })
);
});The { virtual: true } flag is the critical piece — it tells Jest this module doesn't exist on disk, preventing the "cannot find module" error.
Testing Dynamic Imports
Module Federation often involves React.lazy or explicit dynamic imports. Testing these requires Suspense and proper async handling:
// DynamicRemoteLoader.test.js
import { render, screen, waitFor } from '@testing-library/react';
import { Suspense } from 'react';
import DynamicRemoteLoader from './DynamicRemoteLoader';
// Mock the dynamic import function
const mockLoadRemote = jest.fn();
// Successful load
mockLoadRemote.mockResolvedValue({
default: () => <div data-testid="remote-content">Remote Loaded</div>
});
test('loads and renders remote component', async () => {
render(
<Suspense fallback={<div>Loading...</div>}>
<DynamicRemoteLoader loadFn={mockLoadRemote} remoteName="cart" />
</Suspense>
);
expect(screen.getByText('Loading...')).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByTestId('remote-content')).toBeInTheDocument();
});
});
test('shows error state when remote fails to load', async () => {
mockLoadRemote.mockRejectedValue(new Error('Network error'));
render(
<Suspense fallback={<div>Loading...</div>}>
<DynamicRemoteLoader loadFn={mockLoadRemote} remoteName="cart" />
</Suspense>
);
await waitFor(() => {
expect(screen.getByText('Failed to load cart')).toBeInTheDocument();
});
});
test('retries failed load on user request', async () => {
mockLoadRemote
.mockRejectedValueOnce(new Error('Network error'))
.mockResolvedValueOnce({
default: () => <div>Remote Loaded</div>
});
render(
<Suspense fallback={<div>Loading...</div>}>
<DynamicRemoteLoader loadFn={mockLoadRemote} remoteName="cart" />
</Suspense>
);
await screen.findByText('Failed to load cart');
fireEvent.click(screen.getByText('Retry'));
await screen.findByText('Remote Loaded');
expect(mockLoadRemote).toHaveBeenCalledTimes(2);
});Testing Version Mismatches
Version mismatches are a subtle runtime failure — the shell expects version X of a shared dependency, the remote ships version Y, and things break in unexpected ways. Test for this explicitly.
First, expose the version information from each app:
// versionCheck.js
export function checkSharedDependencyVersions(expectedVersions) {
const issues = [];
for (const [dep, expectedVersion] of Object.entries(expectedVersions)) {
const actualVersion = window.__SHARED_DEPENDENCY_VERSIONS__?.[dep];
if (!actualVersion) {
issues.push({ dep, issue: 'not-found' });
continue;
}
if (!semverSatisfies(actualVersion, expectedVersion)) {
issues.push({ dep, expected: expectedVersion, actual: actualVersion, issue: 'mismatch' });
}
}
return issues;
}Then test the detection logic:
// versionCheck.test.js
import { checkSharedDependencyVersions } from './versionCheck';
describe('shared dependency version checking', () => {
beforeEach(() => {
window.__SHARED_DEPENDENCY_VERSIONS__ = {
react: '18.2.0',
'react-dom': '18.2.0',
};
});
test('returns empty array when all versions match', () => {
const issues = checkSharedDependencyVersions({
react: '^18.0.0',
'react-dom': '^18.0.0',
});
expect(issues).toHaveLength(0);
});
test('reports mismatch when version is out of range', () => {
const issues = checkSharedDependencyVersions({
react: '^17.0.0', // shell expects React 17, remote has 18
});
expect(issues).toHaveLength(1);
expect(issues[0]).toMatchObject({
dep: 'react',
issue: 'mismatch',
expected: '^17.0.0',
actual: '18.2.0',
});
});
test('reports missing dependency', () => {
const issues = checkSharedDependencyVersions({
lodash: '^4.0.0',
});
expect(issues[0].issue).toBe('not-found');
});
});In Webpack's Module Federation config, enforce singleton mode for React to prevent dual-instance issues:
// webpack.config.js
new ModuleFederationPlugin({
shared: {
react: { singleton: true, requiredVersion: '^18.0.0' },
'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
}
})Write a test that verifies the Webpack config itself enforces the right constraints:
// webpackConfig.test.js
const webpackConfig = require('./webpack.config.js');
const mfPlugin = webpackConfig.plugins.find(
p => p.constructor.name === 'ModuleFederationPlugin'
);
test('react is configured as singleton in Module Federation', () => {
expect(mfPlugin._options.shared.react.singleton).toBe(true);
});
test('react version requirement is specified', () => {
expect(mfPlugin._options.shared.react.requiredVersion).toBeDefined();
});Integration Testing with Real Remotes
For integration tests, you want to test against real federated modules. The setup requires running the remote apps as servers:
// jest.integration.config.js
module.exports = {
testMatch: ['**/*.integration.test.{js,jsx}'],
globalSetup: './integration/globalSetup.js',
globalTeardown: './integration/globalTeardown.js',
};// integration/globalSetup.js
const { spawn } = require('child_process');
const waitOn = require('wait-on');
module.exports = async function globalSetup() {
// Start design system remote
global.__DESIGN_SYSTEM_SERVER__ = spawn('npx', ['serve', '-s', 'dist', '-l', '3001'], {
cwd: '../design-system-remote',
stdio: 'pipe',
});
// Start cart remote
global.__CART_SERVER__ = spawn('npx', ['serve', '-s', 'dist', '-l', '3002'], {
cwd: '../cart-remote',
stdio: 'pipe',
});
// Wait for both to be ready
await waitOn({
resources: [
'http://localhost:3001/remoteEntry.js',
'http://localhost:3002/remoteEntry.js',
],
timeout: 30000,
});
};// integration/globalTeardown.js
module.exports = async function globalTeardown() {
global.__DESIGN_SYSTEM_SERVER__?.kill();
global.__CART_SERVER__?.kill();
};The integration tests themselves run in a real browser-like environment with the actual federated modules loaded:
// checkout.integration.test.js
/**
* @jest-environment jsdom
*/
import { loadRemoteModule } from '../src/moduleLoader';
test('can load and render design system Button from real remote', async () => {
// This actually fetches from localhost:3001
const { default: Button } = await loadRemoteModule('designSystem', './Button');
const { container } = render(<Button>Click me</Button>);
expect(container.querySelector('button')).toBeTruthy();
expect(container.querySelector('button').textContent).toBe('Click me');
});Running Integration Tests in CI
The key is building the remote apps before running integration tests. In your CI pipeline:
# .github/workflows/integration-tests.yml
- name: Build remotes
run: |
cd ../design-system-remote && npm run build
cd ../cart-remote && npm run build
- name: Run integration tests
env:
INTEGRATION_TESTS: 'true'
run: npm run test:integrationKeep integration tests in a separate Jest config and run them separately from unit tests. Unit tests should be fast and isolated; integration tests can be slower and run less frequently.
The Practical Split
Use this breakdown for your testing strategy:
- Unit tests with mocks: Every component that consumes federated modules. Fast, run on every commit. These catch consumer bugs.
- Contract tests: Verify that your mocks match the real remote's API. Run when either side changes. These catch drift between mock and reality.
- Integration tests with real remotes: The critical user flows end-to-end. Run in CI against built artifacts. These catch runtime compatibility issues.
The most common mistake is relying only on unit tests with mocks. Mocks can drift from reality. Without integration tests, you'll deploy a shell that imports designSystem/Button with props that were renamed two weeks ago.