diff --git a/src/internal/__tests__/validate-object.spec.ts b/src/internal/__tests__/validate-object.spec.ts new file mode 100644 index 00000000..abc8a7dd --- /dev/null +++ b/src/internal/__tests__/validate-object.spec.ts @@ -0,0 +1,52 @@ +/** + * @file Unit Tests - validateObject + * @module pathe/internal/tests/unit/validateObject + */ + +import ERR_INVALID_ARG_TYPE from '../err-invalid-arg-type' +import testSubject from '../validate-object' + +describe('unit:internal/validateObject', () => { + let name: string + + beforeEach(() => { + name = 'pathObject' + }) + + it('should return true if value is an object', () => { + // Arrange + const cases: Parameters[0][] = [ + {}, + new Date(), + JSON.parse(faker.datatype.json()) + ] + + // Act + Expect + cases.forEach(value => expect(testSubject(value, name)).to.be.true) + }) + + it('should throw if value is not an object', () => { + // Arrange + const cases: Parameters[0][] = [ + faker.datatype.array(), + faker.datatype.bigInt(), + faker.datatype.boolean(), + faker.datatype.boolean(), + faker.datatype.number(), + faker.datatype.string() + ] + + // Act + Expect + cases.forEach(value => { + let error: ERR_INVALID_ARG_TYPE + + try { + testSubject(value, name) + } catch (e: unknown) { + error = e as typeof error + } + + expect(error!).to.be.instanceOf(ERR_INVALID_ARG_TYPE) + }) + }) +}) diff --git a/src/internal/validate-object.ts b/src/internal/validate-object.ts new file mode 100644 index 00000000..783dca4f --- /dev/null +++ b/src/internal/validate-object.ts @@ -0,0 +1,30 @@ +/** + * @file Internal - validateObject + * @module pathe/internal/validateObject + */ + +import ERR_INVALID_ARG_TYPE from './err-invalid-arg-type' + +/** + * Checks if `value` is an object. + * + * Throws {@linkcode ERR_INVALID_ARG_TYPE} if `value` is not an object. + * + * **Note**: Array values are not considered objects. + * + * [1]: https://nodejs.org/api/errors.html#err_invalid_arg_type + * + * @param {unknown} value - Possible object value + * @param {string} name - `value` label + * @return {boolean} `true` if `value` is an object + * @throws {ERR_INVALID_ARG_TYPE} + */ +const validateObject = (value: unknown, name: string): boolean => { + if (typeof value === 'object' && !Array.isArray(value) && value !== null) { + return true + } + + throw new ERR_INVALID_ARG_TYPE(name, 'object', value) +} + +export default validateObject