Discover the steps to effectively utilize Mocha Chai Unit Test for testing a function that requires two string parameters

I recently came across a challenging question while working on my Udacity cloud developer nanodegree. The task is as follows:

// @TODO try creating a method "concat" to concatenate two strings
// it should take two string paramaters.

Here's the code I have come up with so far:

const concat = (str1: string, str2: string) => {

    if (str1.length === 0 || str2.length === 0) { 
        throw new Error('either of the strings are empty'); 
    }

    let result = str1 + ' ' + str2;
    return result; 
};

My current roadblock involves writing tests for a function that requires parameters using Mocha Chai. Despite multiple attempts and hours of searching online, I have yet to figure it out.

Answer №1

Below is the solution for the unit test:

concat.ts:

export const concat = (str1: string, str2: string) => {
  if (str1.length === 0 || str2.length === 0) {
    throw new Error('either of the strings are empty');
  }
  let result = str1 + ' ' + str2;
  return result;
};

concat.test.ts:

import { concat } from './concat';
import { expect } from 'chai';

describe('61353628', () => {
  it('should return the concatenated result', () => {
    const str1 = 'hello';
    const str2 = 'world';
    const actual = concat(str1, str2);
    expect(actual).to.be.equal('hello world');
  });
  it('should throw an error when str1 is empty', () => {
    const str1 = '';
    const str2 = 'world';
    expect(() => concat(str1, str2)).to.throw('either of the strings are empty');
  });

  it('should throw an error when str2 is empty', () => {
    const str1 = 'hello';
    const str2 = '';
    expect(() => concat(str1, str2)).to.throw('either of the strings are empty');
  });
});

Unit test results showing 100% coverage:

  61353628
    ✓ should return the concatenated result
    ✓ should throw an error when str1 is empty
    ✓ should throw an error when str2 is empty


  3 passing (10ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 concat.ts |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------

Source code can be found here: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61353628

Answer №2

The condition in concat.ts already covers the scenarios mentioned in concat.test.ts, so there is no need to duplicate them.

it('throws an error if str1 is empty', () => {
    const str1 = '';
    const str2 = 'world';
    expect(() => concat(str1, str2)).to.throw('either of the strings are empty');
  });

  it('triggers an error when str2 is empty', () => {
    const str1 = 'hello';
    const str2 = '';
    expect(() => concat(str1, str2)).to.throw('either of the strings are empty');
  });
});

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

Implementing the same concept yet yielding diverse variations?

I'm a bit confused as to why a1 is evaluated as false while a2 is considered to be of type boolean. Can someone explain the reasoning behind this discrepancy? type Includes<T extends readonly any[], U> = U extends T[number] ? true : false; type ...

The utilization of 'fs' in the getInitialProps function is not permitted

Running into an issue while trying to access the contents of a parsed file within getInitialProps when my view loads. The error message "Module not found: Can't resolve 'fs'" is being displayed, and this has left me puzzled - especially cons ...

NativeScript Error Code NG8001: Element 'ActionBar' is unrecognized

In my project, the startupscreen module setup is as follows: import { NativeScriptFormsModule } from "@nativescript/angular"; import { NativeScriptCommonModule } from "@nativescript/angular/common"; import { NgModule, NO_ERRORS_SCHEMA } ...

Issue with React Context Provider failing to set value

I am currently diving into React context hooks and encountering an issue that is puzzling me. I have established a user context with the simple string message of "hello user" as follows: import { useContext, createContext } from "react" export ...

Increasing a value within HTML using TypeScript in Angular

I'm working with Angular and I have a TypeScript variable initialized to 0. However, when trying to increment it using *ngFor in my .ts file, the increment is not happening (even though the loop is running correctly). my-page.html <div *ngFor=&quo ...

Steer clear of mentioning unbound methods, as they can lead to accidental scoping errors with 'this' when invoking static methods

I've been working on a method map based on a query from the Stack Overflow post linked here to assist me in dynamically calling a static method. But, I keep encountering this error message: Avoid referencing unbound methods that could lead to uninte ...

Showing data related to a certain value - what's the best way?

I am currently working on a page where I need to display and edit specific user information at /users/524.json. However, I also want to include the working days from another table on the same page. I have provided most of the code below for reference. Unfo ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

Angular 8 delivers an observable as a result following a series of asynchronous requests

I am working on a simple function that executes 3 asynchronous functions in sequence: fetchData() { this.fetchUsers('2') .pipe( flatMap((data: any) => { return this.fetchPosts(data.id); }), fl ...

Prisma designs a personalized function within the schema

In my mongo collection, there is a field named amount. My requirement is to have the amount automatically divided by 100 whenever it is requested. In Django, this can be achieved with a custom function within the model. Here's how I implemented it: cl ...

Styling of Bootstrap HTML element not appearing as expected

Recently, I've been trying out a new approach by embedding Bootstrap components in an iframe. However, despite loading the necessary stylesheet and scripts, the elements seem to be missing their styles. Can anyone shed some light on why this might be ...

Angular 2 - Utilizing a Shared Service for Subscriptions

After referencing this guide: Parent and children communicate via a service I have decided to utilize a shared service instead of EventEmitter. The reason being that EventEmitter only facilitates communication between parent and child components, which do ...

Angular Datatables - Equivalent function for fnInfoCallback

Scenario using Angular Datatables In my previous experience with jQuery, I was able to accomplish the functionality shown in the images below: https://i.sstatic.net/VoT2A.png Each Tab displayed a datatable, with the count of filtered records shown next ...

An issue was encountered while running a production version of an Ionic 2 Android app, as the ngfactory module could not be located

We encountered an error while running an Ionic2 app using the --prod flag. https://i.sstatic.net/LMLtS.png After the splashscreen loads, the screen turns white. The command we executed is: ionic run android --prod We are deploying on a Nexus 5x devi ...

The TypeError: Property 'subscribe' is not readable because it is undefined

Currently, I am developing an Ionic application and encountered the following method that invokes an observable: fetchCountryById(id: number): Promise<Country> { return new Promise((resolve, reject) => { this.obtainCountries().subscri ...

Can you elaborate on the significance of <abc<xyz>> appearing after a function name in TypeScript?

Learning TypeScript has brought me to new discoveries. While exploring a random project online today, I stumbled upon this intriguing piece of code in a TypeScript file: import { Route, useRoute } from "@react-navigation/native" import { NewAppoi ...

"Creating a backend server using Node.js, TypeScript, and g

I am currently in the process of developing a nodejs project that will consist of 3 key services: Gateway Product Order The Product and Order services will perform functions related to their respective names, while the Gateway service will take JSON requ ...

Top choice for React with TypeScript CodeMirror integration

Seeking recommendations for a package that seamlessly integrates with typescript in an existing react application. Specifically, looking to implement codeMirror functionality. Any suggestions? ...

Guide on implementing a cordova plugin in a TypeScript cordova application

In my Cordova project, which utilizes Angular and Typescript, I am facing issues with implementing the juspay-ec-sdk-plugin for Cordova. I have explored possible solutions on StackOverflow related to integrating Cordova plugin in an Angular 4 Typescript ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...