From e0ab43bcdc050ca3cac2adea927817d99700737e Mon Sep 17 00:00:00 2001 From: Marcin Chrzanowski Date: Sat, 15 Jul 2017 22:48:10 -0400 Subject: Throw Error on syntax errors --- __tests__/lexer.test.js | 12 ++++++++++-- __tests__/parser.test.js | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) (limited to '__tests__') diff --git a/__tests__/lexer.test.js b/__tests__/lexer.test.js index 38c880e..b9260b8 100644 --- a/__tests__/lexer.test.js +++ b/__tests__/lexer.test.js @@ -5,8 +5,16 @@ describe('lex', () => { expect(lex('')).toEqual([]) }) - it('signals an error on unexpected input', () => { - expect(lex('q')).toBe('error') + it('throws on unexpected input', () => { + expect(() => { lex('q') }).toThrow(/Syntax error/) + }) + + it('throws on unexpected input at the end', () => { + expect(() => { lex('1d6 `') }).toThrow(/Syntax error/) + }) + + it('throws on unexpected input in the middle', () => { + expect(() => { lex('2d3 + b 3d4') }).toThrow(/Syntax error/) }) describe('ignores whitespace', () => { diff --git a/__tests__/parser.test.js b/__tests__/parser.test.js index 74ca442..f3c6e97 100644 --- a/__tests__/parser.test.js +++ b/__tests__/parser.test.js @@ -1,6 +1,23 @@ const { parse } = require('../src/parser.js') describe('parse', () => { + describe('error handling', () => { + it('throws when a binary operation lacks an argument', () => { + expect(() => { parse('1d') }).toThrow(/Syntax error/) + expect(() => { parse('2+3+') }).toThrow(/Syntax error/) + }) + + it('throws when two binary operations follow each other', () => { + expect(() => { parse('1dd2') }).toThrow(/Syntax error/) + expect(() => { parse('1+d2') }).toThrow(/Syntax error/) + }) + + it('throws when two dice not combined with a binary operation', () => { + expect(() => { parse('(1d4)(1d6)') }).toThrow(/Syntax error/) + expect(() => { parse('1 2') }).toThrow(/Syntax error/) + }) + }) + it('parses a constant', () => { expect(parse('5')).toEqual({ type: 'constant', value: 5 }) }) -- cgit v1.2.3