Reputation: 11
I'm having some trouble understanding branch coverage when it comes to optional chaining with typescript.
Here is my code
type testingType = {
b?: { a?: number };
};
export function example(input: testingType) {
return input.b?.a;
}
Here is the test (just forcing it to pass in order to generate the report)
test('test', () => {
example({});
expect(1).toBe(1);
});
This is the coverage report screenshot (branch coverage 3/4)
I'm trying to wrap my head around why there are 4 branches in total. Shouldn't there be 2 branches instead?
b
definedb
undefined.Upvotes: 0
Views: 2869
Reputation: 6832
There are 3 branches for this:
{b?: { a?: number }}
Which are:
b
undefined): return input
b
defined, and a
undefined: return input.b
(which is { b: {} }
)b
defined and a defined: return input.b.a
which would be { b: { a: SOME_NUMBER} }
Edit:
Here are my test cases:
describe('My group', () => {
test('empty object', () => {
example({});
expect(1).toBe(1);
});
test('only with b', () => {
example({ b: {} });
expect(1).toBe(1);
});
test('all keys', () => {
example({ b: { a: 5 } });
expect(1).toBe(1);
});
});
Upvotes: 1