From f1be1a3462b3252ee45a739781cda196fe59d4b1 Mon Sep 17 00:00:00 2001 From: Janis Lesinskis Date: Fri, 23 Sep 2016 22:45:33 +1000 Subject: [PATCH] Invalid input error message (#540) * Added check for type of expressions passed to parseTree function * Added tests for bad input raising exception * Added test for supported types NOT throwing exception * Added test case for parser taking String objects --- src/parseTree.js | 3 +++ test/katex-spec.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/parseTree.js b/src/parseTree.js index 3adba82..44f38c6 100644 --- a/src/parseTree.js +++ b/src/parseTree.js @@ -9,6 +9,9 @@ var Parser = require("./Parser"); * Parses an expression using a Parser, then returns the parsed result. */ var parseTree = function(toParse, settings) { + if (!(typeof toParse === 'string' || toParse instanceof String)) { + throw new TypeError('KaTeX can only parse string typed expression'); + } var parser = new Parser(toParse, settings); return parser.parse(); diff --git a/test/katex-spec.js b/test/katex-spec.js index af9688d..57aad4e 100644 --- a/test/katex-spec.js +++ b/test/katex-spec.js @@ -1382,6 +1382,33 @@ describe("An HTML font tree-builder", function() { span = "R"; expect(markup).toContain(span); }); + + it("should throw TypeError when the expression is of the wrong type", function() { + expect(function() { + katex.renderToString({badInputType: "yes"}); + }).toThrowError(TypeError); + expect(function() { + katex.renderToString([1, 2]); + }).toThrowError(TypeError); + expect(function() { + katex.renderToString(undefined); + }).toThrowError(TypeError); + expect(function() { + katex.renderToString(null); + }).toThrowError(TypeError); + expect(function() { + katex.renderToString(1.234); + }).toThrowError(TypeError); + }); + + it("should not throw TypeError when the expression is a supported type", function() { + expect(function() { + katex.renderToString("\\sqrt{123}"); + }).not.toThrowError(TypeError); + expect(function() { + katex.renderToString(new String("\\sqrt{123}")); + }).not.toThrowError(TypeError); + }); }); @@ -1878,3 +1905,15 @@ describe("A macro expander", function() { }); }); }); + +describe("A parser taking String objects", function() { + it("should not fail on an empty String object", function() { + expect(new String("")).toParse(); + }); + + it("should parse the same as a regular string", function() { + expect(new String("xy")).toParseLike("xy"); + expect(new String("\\div")).toParseLike("\\div"); + expect(new String("\\frac 1 2")).toParseLike("\\frac 1 2"); + }); +});