NathanPB
NathanPB

Reputation: 735

How to assert types in an array of objects with Chai?

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

Answers (1)

customcommander
customcommander

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`);
  });
});

Going further

This of course doesn't help much if you need to check other things:

  1. The array is not empty
  2. Each object has exactly id, name and modified as properties. No less no more
  3. id is a positive integer
  4. name is not an empty string
  5. ...

For more fined-grained control you should definitely look into .

Upvotes: 2

Related Questions