From ce3c02b63bf8bc807946457c1a9289b8b57b5ee2 Mon Sep 17 00:00:00 2001 From: T-Motion Date: Tue, 4 Feb 2020 18:10:01 +0100 Subject: [PATCH] fix(validator): throw error if getMessage not of type Function --- packages/validate/src/Validator.js | 10 ++++++-- packages/validate/test/Validator.test.js | 29 +++++++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/packages/validate/src/Validator.js b/packages/validate/src/Validator.js index b315934ef..82b78118c 100644 --- a/packages/validate/src/Validator.js +++ b/packages/validate/src/Validator.js @@ -58,8 +58,14 @@ export class Validator { config: this.config, ...data, }; - if (typeof this.config.getMessage === 'function') { - return this.config.getMessage(composedData); + if (this.config.getMessage) { + if (typeof this.config.getMessage === 'function') { + return this.config.getMessage(composedData); + } + throw new Error( + `You must provide a value for getMessage of type 'function', you provided a value of type: ${typeof this + .config.getMessage}`, + ); } return this.constructor.getMessage(composedData); } diff --git a/packages/validate/test/Validator.test.js b/packages/validate/test/Validator.test.js index ea5659498..166b3f428 100644 --- a/packages/validate/test/Validator.test.js +++ b/packages/validate/test/Validator.test.js @@ -1,9 +1,22 @@ import { expect, fixture, html, unsafeStatic, defineCE } from '@open-wc/testing'; -import { LitElement } from '@lion/core'; import sinon from 'sinon'; +import { LitElement } from '@lion/core'; import { ValidateMixin } from '../src/ValidateMixin.js'; import { Validator } from '../src/Validator.js'; +async function expectThrowsAsync(method, errorMessage) { + let error = null; + try { + await method(); + } catch (err) { + error = err; + } + expect(error).to.be.an('Error', 'No error was thrown'); + if (errorMessage) { + expect(error.message).to.equal(errorMessage); + } +} + describe('Validator', () => { it('has an "execute" function returning "shown" state', async () => { class MyValidator extends Validator { @@ -22,6 +35,20 @@ describe('Validator', () => { }).to.throw('You must provide a name like "this.name = \'IsCat\'" for your Validator'); }); + it('throws when executing a Validator that has a getMessage config property with a value not of type function', async () => { + class MyValidator extends Validator { + constructor(...args) { + super(...args); + this.name = 'MyValidator'; + } + } + + await expectThrowsAsync( + () => new MyValidator({}, { getMessage: 'This is the custom error message' })._getMessage(), + "You must provide a value for getMessage of type 'function', you provided a value of type: string", + ); + }); + it('receives a "param" as a first argument on instantiation', async () => { const vali = new Validator('myParam'); expect(vali.param).to.equal('myParam');