tpszhao
tpszhao

Reputation: 11

Typescript optional chaining testing branch count

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?

Upvotes: 0

Views: 2869

Answers (1)

Fcmam5
Fcmam5

Reputation: 6832

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);
  });
});

Upvotes: 1

Related Questions