From 2cc873d91b575ddac6ecb7564a2c4676dbafc397 Mon Sep 17 00:00:00 2001 From: Jarda Snajdr Date: Mon, 4 Mar 2019 16:48:11 +0100 Subject: [PATCH] Add test for reactivity when locale does not change, fix implementation --- packages/i18n-calypso/src/use-translate.js | 12 ++++--- packages/i18n-calypso/test/use-translate.js | 36 +++++++++++++++++++-- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/packages/i18n-calypso/src/use-translate.js b/packages/i18n-calypso/src/use-translate.js index 9af61f16dfc13..e0163b24571cb 100644 --- a/packages/i18n-calypso/src/use-translate.js +++ b/packages/i18n-calypso/src/use-translate.js @@ -4,15 +4,17 @@ import React from 'react'; export default function( i18n ) { - const getLocaleSlug = i18n.getLocaleSlug.bind( i18n ); - const translate = i18n.translate.bind( i18n ); - Object.defineProperty( translate, 'localeSlug', { get: getLocaleSlug } ); + function bindTranslate() { + const translate = i18n.translate.bind( i18n ); + Object.defineProperty( translate, 'localeSlug', { get: i18n.getLocaleSlug.bind( i18n ) } ); + return translate; + } return function useTranslate() { - const [ , setLocaleSlug ] = React.useState( getLocaleSlug ); + const [ translate, setTranslate ] = React.useState( bindTranslate ); React.useEffect(() => { - const onChange = () => setLocaleSlug( getLocaleSlug() ); + const onChange = () => setTranslate( bindTranslate ); i18n.on( 'change', onChange ); return () => i18n.off( 'change', onChange ); }, []); diff --git a/packages/i18n-calypso/test/use-translate.js b/packages/i18n-calypso/test/use-translate.js index fe0dc1af3397a..8bc6e4e865471 100644 --- a/packages/i18n-calypso/test/use-translate.js +++ b/packages/i18n-calypso/test/use-translate.js @@ -22,11 +22,16 @@ describe( 'useTranslate()', () => { let container; beforeEach( () => { + // reset to default locale + 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; @@ -49,9 +54,7 @@ describe( 'useTranslate()', () => { } ); test( 'rerenders after locale change', () => { - // reset to default locale - i18n.setLocale(); - + // render with the default locale act( () => { ReactDOM.render(