What is the best way to simulate a static variable in JavaScript unit testing?

After running the karma coverage test, I achieved a coverage of 99.3%. To reach 100%, I require assistance in testing the else part of the function below:

createCurrencyUnits(): void {
var keys = Object.keys(ObjectsDomainConstants.CURRENCY_UNITS);
for (var i = 0; i < keys.length; i++) {
  if (ObjectsDomainConstants.CURRENCY_UNITS[keys[i]].base_unit === null) {
    // Base unit (like: rupees, dollar etc.).
    createUnit(ObjectsDomainConstants.CURRENCY_UNITS[keys[i]].name, {
      aliases: ObjectsDomainConstants.CURRENCY_UNITS[keys[i]].aliases});
  } else {
    // Sub unit (like: paise, cents etc.).
    createUnit(ObjectsDomainConstants.CURRENCY_UNITS[keys[i]].name, { //<--red line at here
      definition: ObjectsDomainConstants.CURRENCY_UNITS[keys[i]].base_unit,
      aliases: ObjectsDomainConstants.CURRENCY_UNITS[keys[i]].aliases});
  }
}

A suggestion is to mock/override the CURRENCY_UNITS in the test. You may utilize the function/variable provided below:

fromRawInputString(units: any): Units {
  try {
    this.createCurrencyUnits(); //<-- you can see this function call createCurrencyUnits()
  } catch (parsingError) {}
var compatibleUnits = this.toMathjsCompatibleString(units);
if (compatibleUnits !== '') {
  try {
    unit(compatibleUnits);
  } catch (err) {
    throw new Error(err);
  }
}
return new Units(this.fromStringToList(units));}

Here are the CURRENCY_UNITS:

public static CURRENCY_UNITS = {
dollar: {
  name: 'dollar',
  aliases: ['$', 'dollars', 'Dollars', 'Dollar', 'USD'],
  front_units: ['$'],
  base_unit: null
},
rupee: {
  name: 'rupee',
  aliases: ['Rs', 'rupees', '₹', 'Rupees', 'Rupee'],
  front_units: ['Rs ', '₹'],
  base_unit: null
},
cent: {
  name: 'cent',
  aliases: ['cents', 'Cents', 'Cent'],
  front_units: [],
  base_unit: '0.01 dollar'
},
paise: {
  name: 'paise',
  aliases: ['paisa', 'Paise', 'Paisa'],
  front_units: [],
  base_unit: '0.01 rupee'
}};

Below is the code I attempted to test, but encountered issues:

it('should test the CURRENCY_UNITS', () => {
  ObjectsDomainConstants.CURRENCY_UNITS.cent.base_unit = '0.03 dollar';
  ObjectsDomainConstants.CURRENCY_UNITS.paise.base_unit = '0.02 rupee';
  expect(units.fromRawInputString('cent').toDict()).toEqual(
    new Units([{exponent: 1, unit: 'cent'}]).toDict());
  expect(units.fromRawInputString('paise').toDict()).toEqual(
    new Units([{exponent: 1, unit: 'paise'}]).toDict());
  ObjectsDomainConstants.CURRENCY_UNITS.cent.base_unit = '0.01 dollar';
  ObjectsDomainConstants.CURRENCY_UNITS.paise.base_unit = '0.01 rupee';
});

Answer №1

For those seeking the solution I recently discovered, please refer to the following:

it('should verify the CURRENCY_UNITS when the base unit is not set', () => {
  ObjectsDomainConstants.CURRENCY_UNITS.dollar.base_unit = '100 cent';
  expect(units.fromRawInputString('dollar').toDict()).toEqual(
    new Units([{exponent: 1, unit: 'dollar'}]).toDict());
});

it('should examine the CURRENCY_UNITS if the base unit is unset', () => {
  ObjectsDomainConstants.CURRENCY_UNITS.dollar.base_unit = null;
  expect(units.fromRawInputString('dollar').toDict()).toEqual(
    new Units([{exponent: 1, unit: 'dollar'}]).toDict());
});

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

I must design a unique layout for my website

I am creating a webpage with various shapes and elements. However, I am facing a challenge with creating a shape that is commonly used. In platforms like Khan Academy, there is simulated programming where shapes can be easily created with a simple command ...

jQuery DataTable error: Attempted to set property 'destroy' on an undefined object

<script> $('#archiveTable').DataTable({}); </script> <table id="archiveTable" datatable="ng" class="table table-sm" style="color:black"> <!--some code--> </table> This is a snippet of HTML code Upon checking t ...

Executing callback functions after numerous asynchronous calls have been completed

Is there a method to delay the execution of a specific line of code until multiple API calls have all returned? Typically, I follow this pattern: APIService.call(parameter).then(function(response) { // Do something callBack(); }); This approach wo ...

What is the best way to extract and display data from an API response object in my

{ "_metadata": { "uid": "someuid" }, "reference": [ { "locale": "en-us", ... bunch of similar key:value "close_icon_size" ...

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: https://i.sstatic.net/29Sz4.png How it actually loads: https://i.sstatic.net/TdPYM.png My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component ...

The element 'loginToken' is not found within the type '{ loginToken: string; } | { error: Error; } | { username: string; password: string; }'

I'm currently working on creating a reducer using Typescript and Redux, but I keep running into this error: Property 'loginToken' is not recognized in type '{ loginToken: string; } | { error: Error; } | { username: string; password: str ...

Sending data from the LoginComponent to the RootComponent

I am facing a challenge with implementing *ngIf to hide the login/logout option in the navbar based on the user's authentication status. When logged in, I want to hide the logout link. Here is my current setup. app.component.ts import { Component, O ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

It appears that the collection.add() method in connector/node.js only successfully executes one time

Currently, I am experimenting with MySQL Document Store to compare it with our relational tables. To achieve this comparison, I am working on transforming our existing table into a collection. The table contains approximately 320K records that I need to ...

jQuery Counter Effect encountering isNaN error when trying to display a number retrieved from a get API object

I am looking to display the numerical data retrieved from an API using JSON. I want to incorporate a counter effect that displays "isNaN" if necessary. The API URL returns an object with the total number saved in data.data. Can anyone assist me with achi ...

`Get the height of a specific element within a FlatList using the index property in React Native`

I'm currently exploring a workaround for the initialScrollIndex issue in FlatList that is not functioning correctly. I attempted to use getItemLayout to address this, but encountered a new problem - my elements inside the FlatList have varying heights ...

Transfer spoken words into a textbox using the keyboard-microphone feature on an iPad or mobile device

When we tap on a textbox on an iPad or mobile device in a web browser, the keyboard pops up on the screen. We have the option to choose the microphone and dictate the text directly into the input box using our voice instead of typing. Since speech convers ...

inquiry on php function properties

I have a PHP file containing two functions. <?php function first () { //in real case more conditions echo "first"; return true; } function second () { //in real case more conditions echo "second"; return true; } first(); second(); ?> And in an ...

`troubles integrating external modules in nuxt application`

Just starting with nuxt and incorporating it with vuetify. My aim was to integrate a Google Places Autocomplete feature, so I stumbled upon this: vuetify-google-autocomplete. It seemed simple enough to implement. But turns out it's not that straightfo ...

Listener for clicking on a marker in Google Maps

Trying to add a click event to Google Map markers in my Cordova app has proven to be quite challenging. The recommended ways mentioned in the documentation don't seem to work, unless I make the marker draggable - which is not an option for me. It seem ...

Retrieving a distinct value from an Observable

I am currently attempting to extract the monthlyFee value from this specific response body. ...

Error in Typescript: 'SyncClient' not found in Twilio

While working on my Ionic app, I encountered an issue every time I attempted to use the twilio-chat library in my project through npm install. The error consistently appeared in the .d.ts files. Here is how I imported it in my provider : import { Client ...

Why does console.log in JavaScript exhibit different behaviors as evidenced by the code?

Exploring the behavior of console.log(obj) compared to console.log("obj"+"\n"+obj) in the code snippet below reveals two distinct output outcomes. const obj = new Object() obj.first = 'John' obj.last = 'Doe' obj.alive = true ob ...

Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable. In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff ...