fix(validator): throw error if getMessage not of type Function

This commit is contained in:
T-Motion 2020-02-04 18:10:01 +01:00 committed by Thomas Allmer
parent 2e5d8c740b
commit ce3c02b63b
2 changed files with 36 additions and 3 deletions

View file

@ -58,9 +58,15 @@ export class Validator {
config: this.config,
...data,
};
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);
}

View file

@ -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');