File size: 2,277 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
 * @jest-environment jsdom
 */

import ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';
import i18n, { useTranslate } from '..';

function Label() {
	const translate = useTranslate();
	return translate( 'hook (%(lang)s)', { args: { lang: translate.localeSlug } } );
}

describe( 'useTranslate()', () => {
	let container;

	beforeEach( () => {
		// reset to default locale
		act( () => {
			i18n.setLocale();
		} );

		// create container
		container = document.createElement( 'div' );
		document.body.appendChild( container );
	} );

	afterEach( () => {
		// tear down the container
		ReactDOM.unmountComponentAtNode( container );
		document.body.removeChild( container );
		container = null;
	} );

	test( 'renders a translated string', () => {
		// set some locale data
		i18n.setLocale( {
			'': { localeSlug: 'cs' },
			'hook (%(lang)s)': [ 'háček (%(lang)s)' ],
		} );

		// render the Label component
		act( () => {
			ReactDOM.render( <Label />, container );
		} );

		// check that it's translated
		expect( container.textContent ).toBe( 'háček (cs)' );
	} );

	test( 'rerenders after locale change', () => {
		// render with the default locale
		act( () => {
			ReactDOM.render( <Label />, container );
		} );

		expect( container.textContent ).toBe( 'hook (en)' );

		// change locale and ensure that React UI is rerendered
		act( () => {
			i18n.setLocale( {
				'': { localeSlug: 'cs' },
				'hook (%(lang)s)': [ 'háček (%(lang)s)' ],
			} );
		} );

		expect( container.textContent ).toBe( 'háček (cs)' );
	} );

	test( 'rerenders after update of current locale translations', () => {
		// set some locale data
		act( () => {
			i18n.setLocale( {
				'': { localeSlug: 'cs' },
				'hook (%(lang)s)': [ 'háček (%(lang)s)' ],
			} );
		} );

		// render the Label component
		act( () => {
			ReactDOM.render( <Label />, container );
		} );

		// check that it's translated
		expect( container.textContent ).toBe( 'háček (cs)' );

		// update the translations for the current locale
		act( () => {
			i18n.setLocale( {
				'': { localeSlug: 'cs' },
				'hook (%(lang)s)': [ 'hák (%(lang)s)' ],
			} );
		} );

		// check that the rendered translation is updated
		expect( container.textContent ).toBe( 'hák (cs)' );
	} );
} );