Reputation: 735
I have the following context:
const data = [
{
id: 1,
name: 'thenamefoo',
modified: new Date() // random date
},
{
id: 2,
name: 'namebar',
modified: new Date() // random date
},
...
];
expect(data)...
I want to assert that my data will always be an array that have objects with fixed keys (and types).
For instance, I want something like
expect(data)
.to.be.an('array')
.that.all.have.types.like({
id: Number,
name: String,
modified: Date
});
Is it possible? How? Any libs?
Upvotes: 1
Views: 668
Reputation: 18901
In my opinion you should focus on validating the data instead of toying with a clunky assertion DSL. With simple true/false checks, all you need is the humble assert
:
test('my data is valid', () => {
data.forEach(({id, name, modified}) => {
assert(typeof id === 'number', `${id} is not a number`);
assert(typeof name === 'string', `${name} is not a string`);
assert(modified instanceof Date, `${modified} is not a date`);
});
});
This of course doesn't help much if you need to check other things:
id
, name
and modified
as properties. No less no moreid
is a positive integername
is not an empty stringFor more fined-grained control you should definitely look into jsonschema.
Upvotes: 2