Created
January 21, 2018 16:22
-
-
Save rodrigobdz/2d0fbc0e4cf72748da025ded94f91eb7 to your computer and use it in GitHub Desktop.
Test for missing translations in i18n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import I18n from 'i18n' | |
const deepKeys = require('deep-keys'); | |
const NO_DIFF = null | |
Object.defineProperty(Object.prototype, 'translations', { | |
get: function() { | |
let locale = Object.keys(this)[0] | |
return [ locale, this[locale] ] | |
} | |
}); | |
/** | |
* Checks that both JSON objects have the same keys. | |
* @param {JSON} a Translations for a specific locale | |
* @param {JSON} b Translations for another locale | |
* @return {JSON} Differences between both objects | |
*/ | |
function diff(a,b) { | |
let [ aLocale, aTranslations ] = a.translations | |
let [ bLocale, bTranslations ] = b.translations | |
/** | |
* Extract only keys from JSON | |
* @return {Array} | |
* | |
* Example: | |
* deepKeys({a: {b: {c: 1}}}) | |
* Result: [ 'a.b.c' ] | |
*/ | |
a = deepKeys(aTranslations) | |
b = deepKeys(bTranslations) | |
let missingInB = a.filter(x => b.indexOf(x) == -1) | |
let missingInA = b.filter(x => a.indexOf(x) == -1) | |
if (missingInA.length === 0 && missingInB.length === 0 ) { | |
return NO_DIFF | |
} | |
return { [aLocale]: missingInB, [bLocale]: missingInA } | |
} | |
/** | |
* Checks that all JSON objects have the same keys. | |
* @param {...Array} objects Array of translations | |
* @return {JSON} Differences between JSON objects. | |
*/ | |
function diffs(...objects) { | |
let results = {} | |
objects.forEach(function(o1) { | |
objects.forEach(function(o2) { | |
// Pairwise comparison of objects | |
let diffBetweenObjects = diff(o1,o2) | |
if (diffBetweenObjects !== NO_DIFF) { | |
// Store differences | |
results = {...results, ...diffBetweenObjects} | |
} | |
}) | |
}) | |
return results | |
} | |
/** | |
* Test for equality in translation keys. | |
* @return {Bool} True if all translations have the same keys. | |
*/ | |
test('no missing translations', () => { | |
let formattedTranslations = [] | |
for(let o in I18n.translations) { | |
formattedTranslations.push({[o]: I18n.translations[o]}) | |
} | |
let diff = diffs(...formattedTranslations) | |
expect(diff).toEqual({}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test missing translations in i18n
Check if there are missing keys in multiple JSON objects containing translations for different locales.
Requirements