I have a situation where I need to create a test that calls a function and checks its return value. It returns an object so I have to iterate through it and check 100 or so values for correctness. If one of them fails I want to know which one.
I cannot work out how to do this with vanilla Jest such that the test is self-contained and I get a meaningful error message on a failure.
For example, I can do this: (pseudocode to illustrate, not actual code)
describe('Test for function A', () => {
beforeAll('Create class instance', () => {
this.inst = new MyClass();
});
test('Call function with no parameters', () => {
const value = this.inst.run();
for (each key=value) {
expect(value).toBe(correct); // on failure, doesn't tell me the key, only the value
}
});
});
The problem with this is that if value
is not correct
then the error message is not very helpful, as it doesn't tell me which of the 100 values has the problem.
I can't change to test.each()
because then I get an error saying I have nested test()
calls which is not allowed.
If I use an inner test()
and change the parent test()
to describe()
then the code becomes this:
describe('Test for function A', () => {
beforeAll('Create class instance', () => {
this.inst = new MyClass();
});
describe('Call function with no parameters', () => {
const value = this.inst.run();
for (each value) {
test(`Checking ${value.name}`, () => {
expect(value).toBe(correct);
});
}
});
});
This would give me a detailed error message except this.inst.run()
is called during test set up, before this.inst
has been set by beforeAll()
, so it fails. (Jest runs all the describe()
blocks first, then beforeAll()
, then test()
. This means I call this.inst.run()
first in a describe()
block before the beforeAll()
block creates the class instance.)
Is there any way that this is possible to achieve? To have a test that requires an object created and shared amongst all the child tests, a test group that calls a function to get data for that group, then a bunch of tests within the group?
describe()
, I just omitted them for clarity.