Code coverage report for jsxlate/t.js

Statements: 4.17% (4 / 96)      Branches: 0% (0 / 14)      Functions: 0% (0 / 22)      Lines: 5.48% (4 / 73)      Ignored: none     

All files » jsxlate/ » t.js
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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193    1   1   1                                                                                                                                                                                                                                                             1                                                                                                                      
'use strict';
 
function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }
 
function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); }
 
var jsxlate = require('./jsxlate');
var I = require('immutable');
 
var extractions = {
    'Hello': [],
    '<I18N>Hello</I18N>': ['Hello'],
    'i18n("world")': ['world'],
    '<I18N><a href="foo">tag with only safe attributes</a></I18N>': ['<a href="foo">tag with only safe attributes</a>'],
    '<I18N><a:link href="foo" target="_blank">tag with unsafe attributes</a:link></I18N>': ['<a:link href="foo">tag with unsafe attributes</a:link>'],
    '<I18N><a href="foo" target="_blank" i18n-id="link">tag with unsafe attributes</a></I18N>': ['<a:link href="foo">tag with unsafe attributes</a:link>'],
    '<I18N><SelfClosing i18n-id="foo" attr="attr" /></I18N>': ['<SelfClosing:foo />'],
    '<I18N><SelfClosing /></I18N>': ['<SelfClosing />'],
    '<I18N><SelfClosing:a /><SelfClosing:b /></I18N>': ['<SelfClosing:a /><SelfClosing:b />'],
    '<I18N><Member.Name /></I18N>': ['<Member.Name />'],
    '<I18N><a><b><i>Deeply nested</i> nested <i>nested</i> nested</b> tags</a></I18N>': ['<a><b><i>Deeply nested</i> nested <i>nested</i> nested</b> tags</a>'],
    '<I18N>Cat: {hat}</I18N>': ['Cat: {hat}'],
    '<I18N>And now {a.member.expression}</I18N>': ['And now {a.member.expression}'],
    'var {nested, ...rested} = i18n("hatters"); <I18N>Cat: {nested}</I18N>': ['hatters', 'Cat: {nested}'],
    '<p><I18N>1: {same.name.different.message}</I18N> <I18N>2: {same.name.different.message}</I18N></p>': ['1: {same.name.different.message}', '2: {same.name.different.message}'],
    '<I18N><Pluralize on={count}><Match when="zero">You have no items</Match><Match when="one">You have one item</Match><Match when="other">You have {count} items</Match></Pluralize></I18N>': ['<Pluralize on={count}><Match when="zero">You have no items</Match><Match when="one">You have one item</Match><Match when="other">You have {count} items</Match></Pluralize>']
};
 
exports.testExtraction = function (test) {
    Object.keys(extractions).forEach(function (input) {
        try {
            jsxlate.extractMessages(input);
        } catch (e) {
            console.error(e);
        }
        test.ok(I.is(I.fromJS(extractions[input]), I.fromJS(jsxlate.extractMessages(input))), '\n                 Incorrect extraction for input\n                 ' + input + '\n                 Expected\n                 ' + extractions[input] + '\n                 but got\n                 ' + jsxlate.extractMessages(input) + '\n                 ');
    });
    test.done();
};
 
var translations = {
    'Hello': 'Helo',
    'world': 'byd',
    '<a href="foo">tag with only safe attributes</a>': '<a href="bar">Mae tag sydd <span>wedi</span> dim ond priodoleddau sy\'n ddiogel</a>',
    '<a:link href="foo">tag with unsafe attributes</a:link>': '<a:link href="bar">tag gyda phriodoleddau anniogel</a:link>',
    '<SelfClosing />': 'Translated: <SelfClosing />',
    '<SelfClosing:foo />': 'Translated: <SelfClosing:foo />',
    '<Member.Name />': 'Translated: <Member.Name />',
    'Cat: {nested}': 'Cat : {nested}',
    'hatters': 'hetwyr',
    'And now {a.member.expression}': 'Ac yn awr {a.member.expression}',
    '<Re /><Ordering />': '<Ordering /><Re />',
    'Check out: <Component />': '<Component/> checked out!',
    '<span:stat><ReactIntl.FormattedNumber /></span:stat>opportunities': '<span:stat><ReactIntl.FormattedNumber /></span:stat>oportunidades'
};
 
var expectedResultsFromTranslation = {
    '<I18N>Hello</I18N>': '<I18N>Helo</I18N>;',
    'i18n("world")': '\'byd\';',
    '<I18N><a href="foo">tag with only safe attributes</a></I18N>': '<I18N><a href="bar">Mae tag sydd <span>wedi</span> dim ond priodoleddau sy\'n ddiogel</a></I18N>;',
    '<I18N><a:link href="foo" target="_blank">tag with unsafe attributes</a:link></I18N>': '<I18N><a target="_blank" href="bar">tag gyda phriodoleddau anniogel</a></I18N>;',
    '<I18N><a href="foo" target="_blank" i18n-id="link">tag with unsafe attributes</a></I18N>': '<I18N><a target="_blank" href="bar">tag gyda phriodoleddau anniogel</a></I18N>;',
    '<I18N><SelfClosing i18n-id="foo" attr="attr" /></I18N>': '<I18N>Translated: <SelfClosing attr="attr" /></I18N>;',
    '<I18N><SelfClosing /></I18N>': '<I18N>Translated: <SelfClosing /></I18N>;',
    '<I18N><Member.Name /></I18N>': '<I18N>Translated: <Member.Name /></I18N>;',
    '<I18N>Cat: {nested}</I18N>': '<I18N>Cat : {nested}</I18N>;',
    '<I18N>And now {a.member.expression}</I18N>': '<I18N>Ac yn awr {a.member.expression}</I18N>;',
    'var nested = i18n("hatters"); <I18N>Cat: {nested}</I18N>': 'var nested = \'hetwyr\';\n<I18N>Cat : {nested}</I18N>;',
    '<I18N><Re /><Ordering /></I18N>': '<I18N><Ordering /><Re /></I18N>;',
    '<I18N>Check out: <Component gnar={3 * shnar}/></I18N>': '<I18N><Component gnar={3 * shnar} /> checked out!</I18N>;',
    '<I18N><span:stat><ReactIntl.FormattedNumber value={count} /></span:stat>opportunities</I18N>': '<I18N><span:stat><ReactIntl.FormattedNumber value={count} /></span:stat>oportunidades</I18N>'
};
 
exports.testTranslation = function (test) {
    Object.keys(expectedResultsFromTranslation).forEach(function (original) {
        try {
            jsxlate.translateMessages(original, translations);
        } catch (e) {
            debugger;console.error(e);
        };
        test.ok(I.is(I.fromJS(expectedResultsFromTranslation[original]), I.fromJS(jsxlate.translateMessages(original, translations))), '\n                 Incorrect translation for original\n                 ' + original + '\n                 Expected\n                 ' + expectedResultsFromTranslation[original] + '\n                 but got\n                 ' + jsxlate.translateMessages(original, translations) + '\n                 ');
    });
    test.done();
};
 
var expectedResultsForTranslationBundles = {
    '<I18N>Hello</I18N>': 'function() { return <span>Helo</span>; }',
    'i18n("world")': 'function() { return \'byd\'; }',
    '<I18N><a href="foo">tag with only safe attributes</a></I18N>': 'function() { return <span><a href="bar">Mae tag sydd <span>wedi</span> dim ond priodoleddau sy\'n ddiogel</a></span>; }',
    '<I18N><a:link href="foo" target="_blank">tag with unsafe attributes</a:link></I18N>': 'function() { return <span><a target="_blank" href="bar">tag gyda phriodoleddau anniogel</a></span>; }',
    '<I18N><a href="foo" target="_blank" i18n-id="link">tag with unsafe attributes</a></I18N>': 'function() { return <span><a target="_blank" href="bar">tag gyda phriodoleddau anniogel</a></span>; }',
    '<I18N><SelfClosing i18n-id="foo" attr="attr" /></I18N>': 'function(SelfClosing) { return <span>Translated: <SelfClosing attr="attr" /></span>; }',
    '<I18N><SelfClosing /></I18N>': 'function(SelfClosing) { return <span>Translated: <SelfClosing /></span>; }',
    '<I18N><Member.Name /></I18N>': 'function(Member) { return <span>Translated: <Member.Name /></span>; }',
    '<I18N>Cat: {nested}</I18N>': 'function(nested) { return <span>Cat : {nested}</span>; }',
    '<I18N>And now {a.member.expression}</I18N>': 'function(a) { return <span>Ac yn awr {a.member.expression}</span>; }',
    '<I18N><Re /><Ordering /></I18N>': 'function(Re, Ordering) { return <span><Ordering /><Re /></span>; }'
};
 
exports.testTranslationToRenderer = function (test) {
    Object.keys(expectedResultsForTranslationBundles).forEach(function (original) {
        var messageAst = jsxlate._parseExpression(original);
        var message = jsxlate._extractMessage(messageAst);
        try {
            jsxlate.translatedRendererForMessage(messageAst, translations[message]);
        } catch (e) {
            console.error(e);
        };
        test.ok(expectedResultsForTranslationBundles[original] == jsxlate.translatedRendererForMessage(messageAst, translations[message]), '\n                 Incorrect translation function for original\n                 ' + original + '\n                 Expected\n                 ' + expectedResultsForTranslationBundles[original] + '\n                 but got\n                 ' + jsxlate.translatedRendererForMessage(messageAst, translations[message]) + '\n                 ');
    });
    test.done();
};
 
var shouldNotBeExtractable = ['<I18N>Nested <I18N>message markers.</I18N></I18N>', 'i18n("Not" + "just a string" + "literal")', 'i18n()', 'i18n("Too many", "arguments")', '<I18N><a target="_blank">Unsafe attributes but no id.</a></I18N>', '<I18N><Doubled/>two of the same Component type without ids<Doubled/></I18N>', '<I18N><Doubled:doubled/>two of the same Component type with the same ids<Doubled:doubled/></I18N>', '<I18N>{"string literal"}</I18N>', '<I18N>{arbitrary.expression()}</I18N>', '<I18N>{("non"+"simple").memberExpression}</I18N>', '<I18N>{computed["memberExpression"]}</I18N>'];
 
exports.testErrorsInExtraction = function (test) {
    shouldNotBeExtractable.forEach(function (message) {
        test.throws(function () {
            return jsxlate.extractMessages(message);
        }, message);
    });
    test.done();
};
 
var toBeTranslated = '\nfunction render () {\n    return <p>\n        <I18N>Hello, world. <Component />{foo}{bar.baz}</I18N>\n    </p>\n}\n';
 
// Translations for above source that should cause errors:
var invalidTranslations = ['<a target="_blank">Unsafe attribute</a> <Component />{foo}{bar.baz}', '<a:made-up-id></a:made-up-id><Component />{foo}{bar.baz}', '{random + expression + in + placeholder}<Component />{foo}{bar.baz}', '{non.existant.name}<Component />{foo}{bar.baz}', '<Component /> Duplicated expressions: {foo}{foo}{bar.baz}', 'Missing component. {foo}{foo}{bar.baz}', 'Duplicated component. <Component /> <Component /> {foo}{foo}{bar.baz}'];
var correctTranslation = 'Helo, byd. <Component />{foo}{bar.baz}';
 
exports.testErrorsInTranslation = function (test) {
    var extraction = jsxlate.extractMessages(toBeTranslated)[0];
 
    function translate(translation) {
        jsxlate.translateMessages(toBeTranslated, _defineProperty({}, extraction, translation));
    }
 
    test.doesNotThrow(function () {
        return translate(correctTranslation);
    }, 'Correct translation couldn\'t be translated.');
 
    invalidTranslations.forEach(function (translation) {
        test.throws(function () {
            return translate(translation);
        }, translation);
    });
    test.done();
};
 
var messagesWithFreeVariables = I.List([['<I18N>Hello, world. {/* no variables here bruh */}<Component />{foo}<p>{bar.baz}</p></I18N>', I.Set(['Component', 'foo', 'bar'])], ['<I18N>Hello, world. <Component.SubComponent snoochie={boochies} />{this.bar.baz}</I18N>', I.Set(['Component', 'boochies'])]]);
 
exports.testDetectFreeVariables = function (test) {
    messagesWithFreeVariables.forEach(function (_ref) {
        var _ref2 = _slicedToArray(_ref, 2);
 
        var message = _ref2[0];
        var variables = _ref2[1];
 
        var ast = jsxlate._parse(message);
        var keypaths = jsxlate._keypathsForMessageNodesInAst(ast);
        keypaths.forEach(function (keypath) {
            var messageAst = ast.getIn(keypath);
            test.ok(I.is(jsxlate.freeVariablesInMessageAst(messageAst), variables), jsxlate.freeVariablesInMessageAst(messageAst) + ' did not equal ' + variables + '.');
        });
    });
    test.done();
};
 
var messagesToBeTransformed = I.List([['<I18N>Hello, world. <Component />{foo}<p>{bar.baz}</p></I18N>', '<I18N message={"Hello, world. <Component />{foo}<p>{bar.baz}</p>"} context={this} args={[Component, foo, bar]}' + ' fallback={function() { return <span>Hello, world. <Component />{foo}<p>{bar.baz}</p></span>; }}/>'],
 
// this test ensures whitespace is handled properly
['<I18N>\n            <div>Hello, world. <Component.SubComponent i18n-id="comp.sub" snoochie={boochies} />{this.bar.baz}</div>\n        </I18N>', '<I18N message={"<div>Hello, world. <Component.SubComponent:comp.sub />{this.bar.baz}</div>"} context={this} args={[Component, boochies]}' + ' fallback={function() { return <span>\n            <div>Hello, world. <Component.SubComponent snoochie={boochies} />{this.bar.baz}</div>\n        </span>; }}/>'],
 
// whitespace + escaping quotes
['<I18N>Hello, \n"world".</I18N>', '<I18N message={"Hello, \\n\\"world\\"."} context={this} args={[]}' + ' fallback={function() { return <span>Hello, \n"world".</span>; }}/>'], ['i18n(\'Well golly gee\')', 'i18n(\'Well golly gee\')'], ['i18n(\'Well "golly" gee\')', 'i18n(\'Well "golly" gee\')'], ['i18n(\'Well \\\'golly\\\' gee\')', 'i18n(\'Well \\\'golly\\\' gee\')']]);
 
exports.testMessageNodeTransformation = function (test) {
    messagesToBeTransformed.forEach(function (_ref3) {
        var _ref32 = _slicedToArray(_ref3, 2);
 
        var message = _ref32[0];
        var transformed = _ref32[1];
 
        var ast = jsxlate._parse(message);
        var keypaths = jsxlate._keypathsForMessageNodesInAst(ast);
        keypaths.forEach(function (keypath) {
            test.ok(transformed === jsxlate._transformMessageNode(ast.getIn(keypath)), jsxlate._transformMessageNode(ast.getIn(keypath)) + ' did not equal ' + transformed + '.');
        });
    });
    test.done();
};