Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 2 additions & 9 deletions src/lib/util/assertString.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
export default function assertString(input) {
const isString = typeof input === 'string' || input instanceof String;

if (!isString) {
let invalidType = typeof input;
if (input === null) invalidType = 'null';
else if (invalidType === 'object') invalidType = input.constructor.name;

throw new TypeError(`Expected a string but received a ${invalidType}`);
}
if (input === undefined) throw new TypeError(`Expected a string but received a ${input}`);
if (input.constructor.name !== 'String') throw new TypeError(`Expected a string but received a ${input.constructor.name}`);
}
24 changes: 24 additions & 0 deletions test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
*/
import assert from 'assert';
import typeOf from '../src/lib/util/typeOf';
import assertString from '../src/lib/util/assertString';


describe('Util', () => {
it('should validate different typeOf', () => {
Expand All @@ -18,3 +20,25 @@ describe('Util', () => {
assert.notStrictEqual(typeOf([]), 'object');
});
});

describe('assertString', () => {
it('Should throw an error if no argument is provided', () => {
assert.throws(() => { assertString(); }, TypeError);
});

it('Should throw an error if the argument is not a string, number', () => {
assert.throws(() => { assertString(123); }, TypeError);
});

it('Should throw an error if the argument is not a string, Object', () => {
assert.throws(() => { assertString({}); }, TypeError);
});

it('Should throw an error if the argument is not a string, Array', () => {
assert.throws(() => { assertString([]); }, TypeError);
});

it('Should not throw an error if the argument is a string', () => {
assert.doesNotThrow(() => { assertString('testing'); });
});
});