Skip to content

Commit

Permalink
tests(i18n): throw when no ICU replacement value is given (#9384)
Browse files Browse the repository at this point in the history
  • Loading branch information
exterkamp authored and brendankenny committed Jul 17, 2019
1 parent 31f7142 commit 65a3f7e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
6 changes: 2 additions & 4 deletions lighthouse-core/lib/i18n/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,17 +127,15 @@ function lookupLocale(locale) {
* @param {string} icuMessage
* @param {Record<string, *>} [values]
*/
function _preprocessMessageValues(icuMessage, values) {
if (!values) return;

function _preprocessMessageValues(icuMessage, values = {}) {
const clonedValues = JSON.parse(JSON.stringify(values));
const parsed = MessageParser.parse(icuMessage);
// Throw an error if a message's value isn't provided
parsed.elements
.filter(el => el.type === 'argumentElement')
.forEach(el => {
if (el.id && (el.id in values) === false) {
throw new Error('ICU Message contains a value reference that wasn\'t provided');
throw new Error(`ICU Message contains a value reference ("${el.id}") that wasn't provided`);
}
});

Expand Down
12 changes: 12 additions & 0 deletions lighthouse-core/test/lib/i18n/i18n-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ describe('i18n', () => {
helloSecWorld: 'Hello {in, number, seconds} World',
helloTimeInMsWorld: 'Hello {timeInMs, number, seconds} World',
helloPercentWorld: 'Hello {in, number, extendedPercent} World',
helloWorldMultiReplace: '{hello} {world}',
};
const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);

Expand Down Expand Up @@ -134,5 +135,16 @@ describe('i18n', () => {
const helloPercentStr = str_(UIStrings.helloPercentWorld, {in: 0.43078});
expect(helloPercentStr).toBeDisplayString('Hello 43.08% World');
});

it('throws an error when values are needed but not provided', () => {
expect(_ => i18n.getFormatted(str_(UIStrings.helloBytesWorld), 'en-US'))
.toThrow(`ICU Message contains a value reference ("in") that wasn't provided`);
});

it('throws an error when a value is missing', () => {
expect(_ => i18n.getFormatted(str_(UIStrings.helloWorldMultiReplace,
{hello: 'hello'}), 'en-US'))
.toThrow(`ICU Message contains a value reference ("world") that wasn't provided`);
});
});
});

0 comments on commit 65a3f7e

Please sign in to comment.