-1

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)

coverage report

I'm trying to wrap my head around why there are 4 branches in total. Shouldn't there be 2 branches instead?

  • b defined
  • b undefined.
kelsny
  • 23,009
  • 3
  • 19
  • 48
tpszhao
  • 1
  • 2
  • I would guess that is because there is also `a` that can be defined or undefined, so that would make 2 x 2 = 4? – kelsny Feb 25 '23 at 02:25

1 Answers1

1

There are 3 branches for this:

{b?: { a?: number }}

NYC report

Which are:

  • Empty object (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);
  });
});
Fcmam5
  • 4,888
  • 1
  • 16
  • 33
  • Did you use all 3 cases for that coverage? I only had one test case in the question above. I'm trying to figure out how that one case covered 3 branches though. Maybe jest config is messing something up? – tpszhao Feb 25 '23 at 02:52
  • I updated my answer with my test cases – Fcmam5 Feb 25 '23 at 03:14
  • Yes indeed check your jest, babel and ts config – Fcmam5 Feb 25 '23 at 03:17