1.0.0 • Published 4 years ago

@jrh-works/assure v1.0.0

Weekly downloads
-
License
-
Repository
github
Last release
4 years ago

@jrh-works/assure

Simple Node.js object property validations, with companion Chai assertions.

Installation

npm install @jrh-works/assure

The Validation Function

Usage

const { assureProperties } = require('@jrh-works/assure')

Syntax

assureProperties(properties, target)

Example Usage

const object = { a: 1, b: 2, c: 3 }

assureProperties([ 'a', 'b', 'c' ], { of: object, type: 'arbitrary' })

Arguments

NameTypeDescription
propertiesArrayA list of properties to validate.
targetObject: TargetInformation about the object to validate.

Returns

TypeDescription
ObjectThe targeted object.

Exceptions

Throws a standard Error if all properties are not present in the target object.


The Target Object

AttributeTypeDescription
ofObjectThe object to validate.
typeString (optional)A name for the type of object to include in error messages.

Chai Assertions

const chai = require('chai')
const { isAssured } = require('@jrh-works/assure')

chai.use(isAssured)

.assuredBy()

Checks if all an object's properties are assured within a test function.

Syntax

assuredBy(test, exclusions)

Arguments

NameTypeDescription
testFunctionA testing function which will be passed one or more invalid version(s) of an object.
exclusionsObject: ExclusionsFields not to validate.

Example Usage

function eat(food) {
  assureProperties([ 'flavor', 'temperature' ], { of: food })
}

// Passing test.
it('only accepts valid foods', () => {
  expect({ flavor: 'salty', temperature: 'hot', texture: 'smooth' }).to.be.assuredBy(invalidObject => {
    eat(invalidObject)
  }, { exclude: 'texture' })
})

// Failing test.
it('only accepts valid foods', () => {
  expect({ color: 'brown' }).to.be.assuredBy(invalidObject => {
    eat(invalidObject)
  })
})

The Exclusions Object

AttributeTypeDescription
excludeArrayA list of fields to exclude from validation.

.assuredByAsync()

The same as .assuredBy(), but accepts an asynchronous test function.

Example Usage

async function sendDataAbout(food) {
  assureProperties([ 'flavor', 'temperature' ], { of: food })
  await MyFoodAPI.post({ food })
}

// Passing test.
it('only accepts valid foods', () => {
  return expect({ flavor: 'salty', temperature: 'hot', texture: 'smooth' }).to.be.assuredByAsync(async (invalidObject) => {
    await sendDataAbout(invalidObject)
  }, { exclude: 'texture' })
})

// Failing test.
it('only accepts valid foods', () => {
  return expect({ color: 'brown' }).to.be.assuredByAsync(async (invalidObject) => {
    await sendDataAbout(invalidObject)
  })
})