Testing the branch count of optional chaining in Typescript

I am struggling to grasp the concept of branch coverage, especially when it involves optional chaining in TypeScript.

Below is my code snippet:

type testingType = {
   b?: { a?: number };
};
 
export function example(input: testingType) {
   return input.b?.a;
}

And here is the test I wrote, although it's just for passing purposes to generate the report:

test('test', () => {
   example({});
   expect(1).toBe(1);
});

The screenshot below shows the coverage report with 3 out of 4 branches covered:

I am puzzled as to why there are a total of 4 branches. Shouldn't it be only 2 branches?

  • b defined
  • b undefined.

Answer №1

There are 3 different scenarios to consider:

{b?: { a?: number }}

The possible outcomes are as follows:

  • If an empty object (b is not defined): return input
  • If b is defined but a is not: return input.b (which will result in { b: {} })
  • If both b and a are defined: return input.b.a, resulting in { b: { a: SOME_NUMBER} }

Edit:

Here are the test cases that I have set up:

describe('Test suite', () => {
  test('Empty object', () => {
    example({});
    expect(1).toBe(1);
  });

  test('Only with b', () => {
    example({ b: {} });
    expect(1).toBe(1);
  });

  test('All keys provided', () => {
    example({ b: { a: 5 } });
    expect(1).toBe(1);
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to eliminate properties in typescript without relying on the option feature?

I am struggling with removing properties in TypeScript. type Person<GN> = { getName: GN extends never ? never : GN, } const foo = <GN>(person: Person<GN>) => person const first = foo({}) // This should work const second = fo ...

What does the reportProgress function do in HTTP services with JavaScript?

Can someone explain the functionality of reportProgress in JavaScript, specifically when used with Angular Typescript? I am having trouble finding documentation on this. return this.httpClient.request<ProductResponse>('get',`${this.basePath ...

Angular input box with integrated datepicker icons displayed inside

Currently, I have an input field and a datepicker displayed in a row. However, I need to show an icon inside the input box instead. Here is my code: <div class="mb-2" style=" float: left;" class="example-full-width" class= ...

Writing tests with enzyme for material-ui Radio components involves setting up a testing environment with Jest

I've implemented RadioGroup from material UI and now I'm trying to write test code using jest and enzyme. Here is the code snippet: import React from "react"; import Radio from "@material-ui/core/Radio"; import RadioGroup from ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

Struggling to run Jest tests on ajax modules that utilize axios

I am facing an issue while testing a function called status from the module ajax.js using Jest. export const status = ({loginUrl='/', logoutUrl='/'}) => { return axios.get(`/auth?login=${loginUrl}&logout=${logoutUrl}`); }; In ...

How can I sort by the complete timestamp when using the Antd table for dates?

I have an item in my possession. const data: Item[] = [ { key: 1, name: 'John Brown', date: moment('10-10-2019').format('L'), address: 'New York No. 1 Lake Park', }, { ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

Utilizing TypeScript with Svelte Components

I've been struggling to implement <svelte:component /> with Typescript without success. Here's my current attempt: Presentation.svelte <script lang="ts"> export let slides; </script> {#each slides as slide} & ...

Could not load ngx-restangular due to an error: (SystemJS) Module not yet loaded while trying to load "@angular/core"

Recently, I made the switch from using the AngularJS 'restangular' library to the Angular 'ngx-restangular' library during an upgrade from AngularJS to Angular. However, after the transition, I encountered an unexpected error along wit ...

Debugging TypeScript code in VS Code by stepping into a library function within the Node.js debugger

After developing a TypeScript library and its corresponding testing program, I have implemented source maps for both projects. Utilizing the node.js debugger, I am now faced with an issue. While debugging my TypeScript code in the program is successful, t ...

Extension for VSCode: Retrieve previous and current versions of a file

My current project involves creating a VSCode extension that needs to access the current open file and the same file from the previous git revision/commit. This is essentially what happens when you click the open changes button in vscode. https://i.stack. ...

Experimenting with Enzyme and Jest for testing the functionality of Material-UI's Select control

Encountering a challenge with testing Material-UI select option. Attempted to ensure all options are loaded in the control, yet when using console log debug, nothing appears on the options elements. Noticed that the menu items for Material-UI render at th ...

Utilizing generics within a function

Can you help me understand why I am getting an error message that says "Type 'AbstractPopup' is not assignable to type T" when using the return statement in the popupFactory(...) method? This code is just a test example for learning how generics ...

Next.js Enhanced with Google Analytics

I've been experimenting with integrating Google Analytics into Next.js, following a tutorial on YouTube - https://www.youtube.com/watch?v=lMSBNBDjaH8 Following the instructions in the video, I added these two scripts in _document.js: <script async ...

Angular: utilizing input type="date" to set a default value

Looking for a way to filter data by date range using two input fields of type "date"? I need these inputs to already display specific values when the page loads. The first input should have a value that is seven days prior to today's date, while the ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

Is there a way to retrieve the chosen value from a select element?

How do I retrieve the chosen value from a select element? In my select.component.ts file: export class PfSelectComponent implements OnInit { constructor() { } ngOnInit() { } @Input() options : Array<Object>; } Contents of select.compon ...

What methods can TypeScript employ to comprehend this situation?

There's an interesting scenario when it comes to assigning a variable of type unknown to another variable. TypeScript requires us to perform type checking on the unknown variable, but how does TypeScript handle this specific situation? It appears that ...

Expanding IntelliSense and helpful tooltips in VSCode for JavaScript and TypeScript by utilizing Node.js for a deeper understanding

As a beginner in programming, specifically in JS/TS, I've been experimenting with node.js and have encountered a puzzling issue with the IntelliSense or 'helptext' feature in VSCode. For instance, when attempting to use fs.open(), I receive ...