Skip to content

Instantly share code, notes, and snippets.

@Michaelvilleneuve
Created August 8, 2018 10:14
Show Gist options
  • Save Michaelvilleneuve/8808ba2775536665d95b7577c9d8d5a1 to your computer and use it in GitHub Desktop.
Save Michaelvilleneuve/8808ba2775536665d95b7577c9d8d5a1 to your computer and use it in GitHub Desktop.
Jest tests to check for missing translations, unused keys and incomplete translation files
/* eslint-disable */
import fr from 'config/locales/fr';
import en from 'config/locales/en';
import { exec } from 'child_process';
describe('i18n', () => {
test('Translations keys are the same for every language', () => {
const translationKeysEn = iterate(en, '', []);
const translationKeysFr = iterate(fr, '', []);
expect(translationKeysFr).toEqual(translationKeysEn);
});
test('There should not be unused keys', async () => {
const translationKeysEn = iterate(en, '', []);
let everyStringsAreUsed = true;
for (let i = 0; i < translationKeysEn.length; i += 1) {
await new Promise(resolve => {
exec(`grep -rnw './src' -e '${translationKeysEn[i]}'`, (_, stdout) => {
if (everyStringsAreUsed) everyStringsAreUsed = !(stdout == '');
if (stdout == '')
console.warn(`[I18n] Could not find '${translationKeysEn[i]}' in 'src' folder`);
resolve();
});
});
}
expect(everyStringsAreUsed).toBeTruthy();
});
test('There are no missing keys', done => {
exec(`grep "I18n.t(.*\'" -ohrw './src' | grep -o "'.*"`, (_, stdout) => {
const allTranslationsDefined = iterate(en, '', []);
const allTranslationsUsed = stdout.replace(new RegExp("'", 'g'), '').split('\n');
allTranslationsUsed.splice(-1, 1);
for (let i = 0; i < allTranslationsUsed.length; i += 1) {
expect(allTranslationsDefined).toContainEqual(allTranslationsUsed[i]);
}
done();
});
});
});
function iterate(obj, stack, array) {
for (const property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] === 'object') {
iterate(obj[property], `${stack}.${property}`, array);
} else {
array.push(`${stack.slice(1)}.${property}`);
}
}
}
return array;
}
@Dakuan
Copy link

Dakuan commented Feb 1, 2021

chapeau 👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment