Skip to content

Instantly share code, notes, and snippets.

@bdcarr
Created April 15, 2020 05:35
Show Gist options
  • Save bdcarr/1216b0d639420bcd9c98c894bbd60048 to your computer and use it in GitHub Desktop.
Save bdcarr/1216b0d639420bcd9c98c894bbd60048 to your computer and use it in GitHub Desktop.
`chai` plugins for making assertions about Deputy objects
/**
* A collection of `chai` plugins for making assertions about Deputy objects.
* @author Bryce Carr
*/
const stringify = require('./stringify')
module.exports = function(chai, utils) {
const Assertion = chai.Assertion
/**
* If variable under test is an object:
* Asserts that an object has a property `PayRule` with specified `Id`.
* Intended for use on `PayReturn` objects.
*
* If variable under test is an array:
* Asserts that the array has at least one object with property 'PayRule' with specified 'Id.
* Intended for use on arrays of PayReturns, i.e. like you'd get by querying all PayReturns for a Timesheet.
* @param payruleId
* @param msg Message to print on error
*/
const payrule = function(payruleId, msg) {
const obj = this._obj,
test = new Assertion(obj, msg)
utils.flag(test, 'ssfi', true)
if (Array.isArray(obj)) {
new Assertion(obj.length).is.at.least(1)
utils.transferFlags(this, test, false)
let foundReturn
obj.some(payReturn => {
new Assertion(payReturn).has.property('PayRule')
if (payReturn.PayRule === payruleId) {
foundReturn = payReturn
return true
}
})
if (foundReturn) { // Set the object to the payreturn so we can assert on it later in the chain
utils.flag(this, 'object', foundReturn)
}
test.assert(
foundReturn,
`expected at least one of the given PayReturns to have PayRule ${payruleId}:\n${JSON.stringify(obj, null, 4)}`,
`expected none of the given PayReturns to have PayRule ${payruleId}:\\n${JSON.stringify(obj, null, 4)}`
)
} else {
new Assertion(obj).has.property('PayRule')
utils.transferFlags(this, test, false)
test.assert(
obj.PayRule === payruleId,
`expected ${stringify(obj)} to have PayRule #{exp} but got #{act}`,
`expected ${stringify(obj)} to not have PayRule #{act}`,
payruleId, // expected
obj.PayRule // actual
)
}
}
const Value = function(value, msg) {
const obj = this._obj,
test = new Assertion(obj, msg)
new Assertion(obj).has.property('Value')
utils.flag(test, 'ssfi', true)
utils.transferFlags(this, test, false)
test.assert(
obj.Value === value,
`expected ${stringify(obj)} to have Value: #{exp} but got #{act}`,
`expected ${stringify(obj)} to have Value property not equal to #{exp}`,
value, // expected
obj.Value // actual
)
}
Assertion.addMethod('payrule', payrule)
Assertion.addMethod('Value', Value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment