diff --git a/lib/rules/no-raw-text.js b/lib/rules/no-raw-text.js index d2e07ef..8bece52 100644 --- a/lib/rules/no-raw-text.js +++ b/lib/rules/no-raw-text.js @@ -46,9 +46,28 @@ const hasAllowedParent = (parent, allowedElements) => { function create(context) { const options = context.options[0] || {}; + const templateLiteralValue = (node) => { + const firstExpression = node.expressions[0]; + + // A template literal with no interpolations has an empty `expressions`, so + // there is no expression to name. Describe the literal text instead, which + // matches how a plain string expression is reported. + if (!firstExpression) { + return node.quasis.map((quasi) => quasi.value.cooked).join('').trim(); + } + + if (firstExpression.type === 'Identifier') { + return `TemplateLiteral: ${firstExpression.name}`; + } + + // Member expressions, calls and the like have no `.name`, which previously + // rendered as `TemplateLiteral: undefined`. + return `TemplateLiteral: ${context.getSourceCode().getText(firstExpression)}`; + }; + const report = (node) => { const errorValue = node.type === 'TemplateLiteral' - ? `TemplateLiteral: ${node.expressions[0].name}` + ? templateLiteralValue(node) : node.value.trim(); const formattedErrorValue = errorValue.length > 0 diff --git a/tests/lib/rules/no-raw-text.js b/tests/lib/rules/no-raw-text.js index 311cfca..6f310a7 100644 --- a/tests/lib/rules/no-raw-text.js +++ b/tests/lib/rules/no-raw-text.js @@ -147,6 +147,34 @@ const tests = { message: 'Raw text (TemplateLiteral: text) cannot be used outside of a tag', }], }, + { + // A template literal with no interpolations used to throw: + // `Cannot read properties of undefined (reading 'name')` + code: ` + export default class MyComponent extends Component { + render() { + return ({\`some text\`}); + } + } + `, + errors: [{ + message: 'Raw text (some text) cannot be used outside of a tag', + }], + }, + { + // A non-Identifier interpolation has no `.name`, so this used to report + // `Raw text (TemplateLiteral: undefined)`. + code: ` + export default class MyComponent extends Component { + render() { + return ({\`\${this.props.text}\`}); + } + } + `, + errors: [{ + message: 'Raw text (TemplateLiteral: this.props.text) cannot be used outside of a tag', + }], + }, { code: ` export default class MyComponent extends Component {