Reputation: 29
I am rewriting some tests and I have a question. Lets say that I have an object with 10 key/value pairs. Some values are strings and some are numbers.
What I do not want to do is check every key/value separately but rather check all strings and numbers together.
So is there a better way to do this:
expect(a).to.have.property(“b”).that.is.a(“string”).and.not.empty;
expect(a).to.have.property(“c”).that.is.a(“string”).and.not.empty;
expect(a).to.have.property(“d”).that.is.a(“number”);
expect(a).to.have.property(“e”).that.is.a(“number”);
I would like to group the first two and last two in one assertion. Is this doable?
Many thanks!
Upvotes: 0
Views: 399
Reputation: 33730
You can use Array.prototype.every()
with the assert
function, like in this example code:
import {assert} from 'chai';
const a = {
b: 'hello',
c: 'world',
d: 1,
e: 2,
};
// The property names which correspond to the string values:
const strProps: (keyof typeof a)[] = ['b', 'c' /* etc. */];
assert(
strProps.every(key => (
key in a
&& typeof a[key] === 'string'
&& (a[key] as string).length > 0
)),
'Your string property error message here',
);
// The property names which correspond to the number values:
const numProps: (keyof typeof a)[] = ['d', 'e' /* etc. */];
assert(
numProps.every(key => key in a && typeof a[key] === 'number'),
'Your number property error message here',
);
Upvotes: 1