Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 4 additions & 1 deletion src/lib/util/assertString.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
export default function assertString(input) {
if (input === undefined || input === null) 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}`);
if (typeof input !== 'string' && Object.prototype.toString.call(input) !== '[object String]') {
let inputConstructorName = input?.constructor?.name ? input.constructor.name : typeof input;
throw new TypeError(`Expected a string but received a ${inputConstructorName}`);
}
}
17 changes: 17 additions & 0 deletions test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,28 @@ describe('assertString', () => {
assert.throws(() => { assertString([]); }, TypeError);
});

it('Should throw an error if argument provided is an Object pretending to be a \'string\'', () => {
assert.throws(() => { assertString({ constructor: { name: 'string' } }); }, TypeError);
});

it('Should throw an error if argument provided is an Object pretending to be a \'String\'', () => {
assert.throws(() => { assertString({ constructor: { name: 'String' } }); }, TypeError);
});

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

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

it('Should not throw an error if the argument is a boxed string', () => {
// eslint-disable-next-line no-new-wrappers
assert.doesNotThrow(() => { assertString(new String('antidisestablishmentarianism')); });
});

it('Should use typeof as fallback in error message when input has no constructor name', () => {
assert.throws(() => { assertString(Object.create(null)); }, /^TypeError: Expected a string but received a object$/);
});
});
Loading