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 the error message "undefined is not a function" while attempting to retrieve JSON data

I'm running into some issues with retrieving data from a PHP file. Upon calling the variable msg[0}, I'm getting an undefined error even though it should have been filled in during the JSON request. The JavaScript code is provided below, and you ...

Export interface for material-ui wrapper to cast any type in TypeScript (React)

I work with React using TypeScript. Recently, I encountered an issue with exporting. I'm creating an interface that encapsulates components from Material-ui. Here is a simplified example: Wrapping.tsx import { default as Component, ComponentProps ...

Leveraging the @Input Decorator in Angular 2

Check out the Angular 2 component code sample below @Component({ selector: 'author-edit', templateUrl:'./author/edit' }) export class AuthorEditComponent implements OnInit{ @Input() author: AuthorModel; fg: FormGroup; c ...

`Accessing information within a nested JSON array``

I'm currently parsing through the JSON data below. While I can extract the id and name fields without any issues, I am encountering a problem when trying to access json.templates[i].dailyemails.length, as it always returns 0. Below is the structure o ...

Using Angular and RxJS5 to refresh data from both HTTP requests and sockets

Here's a specific scenario I need to address: Retrieve route parameters Utilize route parameters to make an HTTP service call Upon receiving a response from the HTTP service, use the same route parameters to invoke a socket service Whenever the sock ...

What could be causing the observable collection to display the correct number of objects, yet have them all appear empty?

I am offering the following service @Injectable() export class LMSVideoResulful { getVideos( enrolmentId : number ) :Observable<Array<Video>> { var x = new Array<Video>(); //https://www.youtube.com/embed/MV0vLcY65 ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Unable to declare a string enum in TypeScript because string is not compatible

enum Animal { animal1 = 'animal1', animal2 = 'animal2', animal3 = 'animal3', animal4 = 'animal4', animal5 = 'animal5' } const species: Animal = 'animal' + num Why does typescr ...

Error TS2322: Cannot assign a variable of type 'number' to a variable of type 'string'

Encountered an issue with TS2322 error while attempting to compile my Angular application. The error occurs when using a variable [link] that represents the index number. When declaring this variable, I use: @Input() link!: string; This link is used as ...

Determining the function return type by analyzing an array of functions

If you have a vanilla JavaScript function that accepts an array of callbacks (each returning an object) and combines their outputs, how can TypeScript be used to determine the return type of this function? While ReturnType is typically used for a single ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

Ways to send JWT in the request header to an Angular6 application

Managing users and sessions through an external application such as a Web Application Firewall (WAF) The external app sends a JWT with user information in the request header to the Angular6 app The Angular6 app needs to extract the information from the req ...

How can one effectively access a nested JSON value in Angular by concatenating all fields?

If we have a JSON stored in the variable person like below: { "firstName": "First Name", "lastName": "Last Name", "address": { "city": "New-York", "street": "Some Street" } } To access the value of street, we would typical ...

Workspace Settings cannot be saved due to an unregistered configuration

I've been attempting to change the StatusBar color in VScode Setting.json using Configuration and Workspace. However, I encountered an error when trying to make the update: Error: Unable to write to Workspace Settings because workbench.colorCustomizat ...

What is the best method for comparing arrays of objects in TypeScript for optimal efficiency?

Two different APIs are sending me arrays of order objects. I need to check if both arrays have the same number of orders and if the values of these orders match as well. An order object looks like this: class Order { id: number; coupon: Coupon; customer ...

Creating Beautiful MDX Layouts with Chakra UI

Currently, I am attempting to customize markdown files using Chakra UI within a next.js application. To achieve this, I have crafted the subsequent MDXComponents.tsx file: import { chakra } from "@chakra-ui/react" const MDXComponents = { p: (p ...

The functionality is verified in Postman, however, it is not functioning properly when accessed from my client's end

I am working on a project where I have a button in my client's application that is supposed to delete a document from a MongoDB collection based on its ID. Here is the backend code for this functionality: index.js: router.post('/deletetask' ...

Error in Angular: Unable to Access Property '..' of null

Having an issue with my Angular project where I keep getting an error message saying "cannot read property of '...' of undefined" whenever I select an employee from the combo box. The '...' represents the index of the selected employee. ...

tips for transferring API JSON response parameters to material ui table

I'm currently working on creating a table with the material UI. My goal is to populate the rows of the table based on the data received from an API response. The challenge I'm facing is that the API response includes an array of objects with mult ...

Utilizing Embedded Jetty for Angular URL rewriting

While deploying a WebSocket and an Angular application with Jetty, everything works fine during development. However, I am facing an issue in production where refreshing the frontend or entering a URL results in a 404 error from the server indicating that ...