react-intl-auto-id-mock
v0.1.0
Published
Auto-generate message IDs for react-intl in tests, allowing you to skip the formatjs babel/swc plugin
Maintainers
Readme
react-intl-auto-id-mock
Auto-generate message IDs for react-intl in tests, allowing you to skip the formatjs babel/swc plugin for ~35% faster test transforms.
The Problem
When using react-intl, you typically use a build plugin (like babel-plugin-formatjs or @swc/plugin-formatjs) to auto-generate message IDs from your defaultMessage strings:
<FormattedMessage defaultMessage="Hello, world!" />
// Plugin transforms to:
<FormattedMessage id="abc123" defaultMessage="Hello, world!" />Without this transform, react-intl throws an error: An 'id' must be provided to format a message.
The problem? These plugins add significant overhead to test transforms:
@swc/plugin-formatjsis a Wasm module that adds ~35% to transform timebabel-plugin-formatjsis even slower
The Solution
This package mocks react-intl to auto-generate IDs at runtime, letting you skip the plugin entirely in tests.
Installation
npm install --save-dev react-intl-auto-id-mockUsage
Vitest
// vitest.setup.ts
import 'react-intl-auto-id-mock/vitest';Then remove the formatjs plugin from your vitest config:
// vitest.config.ts
import react from '@vitejs/plugin-react-swc';
export default defineConfig({
plugins: [
// Remove the formatjs plugin for tests
react(), // instead of react({ plugins: [['@swc/plugin-formatjs', {...}]] })
],
});Jest
// jest.setup.ts
import 'react-intl-auto-id-mock/jest';Auto-detection
If you're not sure which framework you're using, the main entry point auto-detects:
import 'react-intl-auto-id-mock';Custom ID Generation
You can provide a custom ID generator:
import { setupReactIntlMock } from 'react-intl-auto-id-mock/vitest';
setupReactIntlMock({
generateId: (defaultMessage, description) => {
return `test_${defaultMessage.slice(0, 20)}`;
},
});What Gets Mocked
This package wraps the following react-intl exports to auto-generate IDs:
useIntl()- TheformatMessagefunction is wrapped<FormattedMessage>- Props are patched before renderinginjectIntl()- The injectedintl.formatMessageis wrapped
Performance
In our testing, removing the @swc/plugin-formatjs plugin and using this mock reduced:
- Transform time by ~35%
- Overall test duration by ~20%
Requirements
react-intl>= 5.0.0vitest>= 1.0.0 orjest>= 27.0.0
License
MIT
