Encountering a problem with the mock object in Angular 11 unit testing when converting a JSON object to a TypeScript interface

Within my Angular 11 application, I am working with a JSON response and have defined an interface to match the structure of this JSON object. The JSON object looks like this:

{
  "division": {
      "uid": "f5a10d90-60d6-4937-b917-1d809bd180b4",
      "name": "Sales Division",
      "title": "Sales",
      "type": "Form",
      "formFields": [
          {
              "id": 1,
              "name": "firstName",
              "label": "First Name",
              "value": "John"
          },
          {
              "id": 2,
              "name": "lastName",
              "label": "Last Name",
              "value": "Smith"
          }
      ]
   }
}

To represent this JSON object in TypeScript, I have created the following interfaces:

export interface FormField {
   id: number;
   name: string;
   label: string;
   value: string;
}

export interface Division {
   uid: string;
   name: string;
   title: string;
   type: string;
   formFields: FormField[];
}

export interface Division {
   division: Division;
}

I am fetching this JSON response from an API using a service named division.sevice.ts, and everything is functioning correctly. Now, I am attempting to write unit tests for this service in the division.service.spec.ts file. To facilitate testing, I have created a mock object named mockDivisionObj as shown below.

mockDivisionObj = {
  "division": {
      "uid": "f5a10d90-60d6-4937-b917-1d809bd180b4",
      "name": "Sales Division",
      "title": "Sales",
      "type": "Form",
      "formFields": [
          {
              "id": 1,
              "name": "firstName",
              "label": "First Name",
              "value": "John"
          },
          {
              "id": 2,
              "name": "lastName",
              "label": "Last Name",
              "value": "Smith"
          }
      ]
  }
}

While writing these tests, I encountered an error message stating:

Property 'division' is missing in type '{ uid: string; name: string; title: string; type: 
string; formFields: { id: number; name: string; label: string; value: string; }[]; }' but 
required in type 'Division'.

I suspect that there may be an issue with how I have structured the interfaces, but I am struggling to identify the exact cause of the problem. Any assistance on resolving this would be greatly appreciated.

Answer №1

To resolve the issue, I made a simple adjustment by renaming one of the interfaces in the code snippet to 'AppSection' as illustrated below.

export interface FormData {
   id: number;
   name: string;
   label: string;
   value: string;
}

export interface Section {
   uid: string;
   name: string;
   title: string;
   type: string;
   formData: FormData[];
}

export interface AppSection {
   section: Section;
}

The conflicting names for two interfaces were causing an error within the test object's setup.

Answer №2

Your solution seems to be correct. To fix this issue, you may want to consider using the following code snippet =>

  var division = this.mockDivision.division as Division;

Visit the Link: Live Demo link.

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

Encountering difficulties with launching Jest following the installation of selenium-webdriver

In order to test my React application, I have implemented two types of tests. Jest is used for unit testing As I venture into feature testing, I decided to experiment with Cucumber @cucumber/cucumber. Initially, I considered using jest-cucumber, but it ha ...

Ways to extract the body/message of a request from an HttpErrorResponse in Angular using the ErrorHandler

Imagine I make a request to the server using the post method in order to create a new user. In case the server responds with an error, my goal is to retrieve the form data that was submitted along with that request from the ErrorHandler. This information i ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

Encountering a type error when attempting to filter TypeORM 0.3.5 by an enum column that is

I have the following configuration: export enum TestEnum { A = 'A', B = 'B' C = 'C' } @Entity() export class User { @PrimaryGeneratedColumn() id: number @Column({enum: TestEnum}) test: TestEnum } ...

Avoid including line breaks when using JSON_ENCODE to prevent any issues in the

When attempting to add a new record to my JSON file, I encounter an issue where after encoding the files, there are numerous instances of \ and \n. How can I go about removing these unwanted characters? JSON { "clients": [ { ...

Parse a JSON file in Python to make changes to a specific key's value, then proceed to save the updated data and send it

After extracting a JSON object with the following structure: { "board_title": "test", "read_only": false, "isIntegration": false, "board_bgtype": "board_graph", "created": "2017-08-16T06:40:47.158868+00:00", "original_title": "Revised_CID_Temp ...

Guide to customizing the appearance of a Bootstrap Component within an Angular project

Is it possible to completely customize the style/CSS of a component from ng-bootstrap? Here's the issue I'm facing: I have this code... <ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next" style ...

Steps to define a JavaScript mixin in VueJS

Currently, I am working on a Vue project with TypeScript and in need of using a mixin from a third-party library written in JavaScript. How can I create a .d.ts file to help TypeScript recognize the functions defined in the mixin? I have attempted the fol ...

What is the reason that the command `npx create-react-app my-app --typescript` is not providing me with the expected TypeScript files?

I used the command npx create-react-app my-app --typescript to create my React project, but it seems like I still ended up with the default JavaScript boilerplate files. I was expecting to see files with a .tsx or .ts extension and use import * from as R ...

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...

Integrating Angular 2 code into an existing JSF web application

I have a web application developed using JSF and Maven. Currently, the UI is built using JSF and I would like to add new screens using Angular 2 code within the same application while making REST calls. I am unsure about where to integrate the Angular co ...

What could be the reason for the malfunctioning of the basic angular routing animation

I implemented a basic routing Angular animation, but I'm encountering issues where it's not functioning as expected. The animation definition is located in app.component.ts with <router-outlet></router-outlet> and two links that shoul ...

Array of colors for Wordcloud in Angular Highcharts

I am currently utilizing Angular Highcharts 9.1.0 and facing an issue with generating a word cloud that incorporates specific colors. Despite including color values in the array, they do not seem to be applied as intended. Take a look at the code snippet b ...

Creating a DynamoDB table and adding an item using CDK in Typescript

Can anyone guide me on how to add items to a Dynamodb Table using CDK and Typescript? I have figured out the partition/sort keys creation, but I am struggling to find a straightforward solution for adding items or attributes to those items. Additionally, ...

What is the best way to apply styling to the placeholder of an input element using Angular?

Is there a way to achieve something similar in Angular? [style.placeholder.color]="active ? 'white' : 'grey'" I'm looking to bind the placeholder pseudo element of an input element. How can I bind it to the style propert ...

Fill a dynamic form with a date sourced from the ngrx storage

How can I populate a form with data from the store if setValue and patchValue methods are not working? export class MyComponent implements OnInit, OnDestroy { public newsletterToEdit$: Observable<NewNewsletter> = this.store.selectNewsletterToEdi ...

The Json document includes identifiers that start with the dollar sign symbol

I am working with a JSON file that has a structure similar to what you can find here. Within this file, there are keys such as "$schema" and "$ref". Can someone explain the significance of a key name starting with $? ...

Learn how to send an SMS using Angular and Ionic 4 without having to open the native SMS app

I have been actively monitoring the GitHub repository for the Ionic Native SMS plugin at https://github.com/cordova-sms/cordova-sms-plugin. Following the suggested configuration from the repo, I have set it up as follows: var options = { repla ...

`Are There Drawbacks to Utilizing Static JSON Files for Frontend Data?`

Imagine I have a collection of data called members. Each individual member includes attributes like name:string, birthYear:number, favoriteBook:string, and an id:number. To display this information on a website, I create a JSON file that contains all the ...

What is the process for extracting a list of objects from a JSON String that contains various reference units, using a mapper function?

My goal is to extract all selected columns and store them in the database as a Json String. Then, I need to convert them back into a List of Objects and send them back to the UI. The structure of my Json data is shown below. I am specifically looking to ...