|
| 1 | +--- |
| 2 | +id: example-react-intl |
| 3 | +title: React Intl |
| 4 | +--- |
| 5 | + |
| 6 | +> **Note** |
| 7 | +> |
| 8 | +> If you want to combine setupTests with another setup you should check |
| 9 | +> [`setup`](react-testing-library/setup.md) |
| 10 | +
|
| 11 | +## Configuring React-Intl Polyfills |
| 12 | + |
| 13 | +If you're using React-Intl in your project, and you need to load a locale, you |
| 14 | +must load the Polyfills according to that language. |
| 15 | + |
| 16 | +In order to do so, you may use this small setup and/or combine it with other |
| 17 | +setups. |
| 18 | + |
| 19 | +``` |
| 20 | +// src/setupTests.js |
| 21 | +import IntlPolyfill from 'intl' |
| 22 | +import 'intl/locale-data/jsonp/pt' |
| 23 | +
|
| 24 | +const setupTests = () => { |
| 25 | + // https://formatjs.io/guides/runtime-environments/#server |
| 26 | + if (global.Intl) { |
| 27 | + Intl.NumberFormat = IntlPolyfill.NumberFormat |
| 28 | + Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat |
| 29 | + } else { |
| 30 | + global.Intl = IntlPolyfill |
| 31 | + } |
| 32 | +} |
| 33 | +
|
| 34 | +setupTests(); |
| 35 | +``` |
| 36 | + |
| 37 | +A complete example: |
| 38 | + |
| 39 | +```jsx |
| 40 | +import React from 'react' |
| 41 | +import 'jest-dom/extend-expect' |
| 42 | +import { render, cleanup, getByTestId } from 'react-testing-library' |
| 43 | +import { IntlProvider, FormattedDate } from 'react-intl' |
| 44 | +import IntlPolyfill from 'intl' |
| 45 | +import 'intl/locale-data/jsonp/pt' |
| 46 | + |
| 47 | +const setupTests = () => { |
| 48 | + // https://formatjs.io/guides/runtime-environments/#server |
| 49 | + if (global.Intl) { |
| 50 | + Intl.NumberFormat = IntlPolyfill.NumberFormat |
| 51 | + Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat |
| 52 | + } else { |
| 53 | + global.Intl = IntlPolyfill |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +const FormatDateView = () => { |
| 58 | + return ( |
| 59 | + <div data-testid="date-display"> |
| 60 | + <FormattedDate |
| 61 | + value="2019-03-11" |
| 62 | + timeZone="utc" |
| 63 | + day="2-digit" |
| 64 | + month="2-digit" |
| 65 | + year="numeric" |
| 66 | + /> |
| 67 | + </div> |
| 68 | + ) |
| 69 | +} |
| 70 | + |
| 71 | +const renderWithReactIntl = component => { |
| 72 | + return render(<IntlProvider locale="pt">{component}</IntlProvider>) |
| 73 | +} |
| 74 | + |
| 75 | +setupTests() |
| 76 | +afterEach(cleanup) |
| 77 | + |
| 78 | +test('it should render FormattedDate and have a formated pt date', () => { |
| 79 | + const { container } = renderWithReactIntl(<FormatDateView />) |
| 80 | + expect(getByTestId(container, 'date-display')).toHaveTextContent('11/03/2019') |
| 81 | +}) |
| 82 | +``` |
0 commit comments