I have a jest test that retrieves a list from my object under test and now I want to iterate over the list, checking that each entry meets certain conditions.
Like so:
test('mytest', () => {
const underTest = ...
underTest.doThisAndThat();
expect(underTest.bla()).toBe('blub');
...
const theList = underTest.getListOfDetails();
for(const listElement of theList) {
expect(listElement.hairColor).toBeDefined();
}
});
When the test fails in the loop, jest will report that we expected 'defined' but got undefined. But now I have to change the test code to find out which list element failed the condition.
My current approach is instead of using expect, throw an AssertionError, like so:
test('mytest', () => {
const underTest = ...
underTest.doThisAndThat();
expect(underTest.bla()).toBe('blub');
...
const theList = underTest.getListOfDetails();
for(const listElement of theList) {
if(typeof listElement.hairColor === 'undefined') {
throw new AssertionError({
message: theList.name + ' had no hairColor',
});
}
}
});
While this works, I find this not very nice to code, especially when I have to check many conditions on the listElement.
So my question is: Is there a way to give the expect()... matcher a 'context name' easily?
A way that works is with the describe.each loop, however this structures the whole test differently in the way that I need to split up the test into two tests, one that tests single properties of the underTest object, and another that does the loop.
Unlike in Is It Possible To Extend A Jest / Expect Matcher , I would not want to write an expect.extend for each of these loops.