Ways to fake an interface using Jest without needing to instantiate it

While Kotlin supports this, I haven't been able to find a way to achieve the same in Jest. My problem arises from having intricate interfaces and arrays of these interfaces where specifying all attribute values is not ideal. Here's an example of what I'm aiming for:

 interface User {
  name: string
  lastname: string
  age: number
  phone: string
  password: string
  friend: User[] | undefined
}

const user: User = mock()

user.age = 35

incrementAge(user)

expect(user.age).toBe(36)

Answer №1

JavaScript doesn't natively support interfaces like TypeScript does, as they are only used for type checking during compilation in TypeScript. Because of this limitation, generating a correct mock based on an interface in JavaScript runtime is not possible. However, it can be achieved with classes.

If you need to create a mock without instantiating an object, you can cast an empty object to the desired type. Keep in mind that the cast object won't have any default properties, and accessing them will return undefined.

 interface User {
  name: string
  lastname: string
  age: number
  phone: string
  password: string
  friend: User[] | undefined
}

const user = {} as User;
user.age = 35 // this works
user.name = undefined; // this fails due to wrong type

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

Effortless JSON parsing with Angular 2 Http GET request

After sending an HTTP get request to my server API, I am attempting to parse the JSON object that is returned. Below is the code snippet for the Http call: getPayoutReport(param1, param2, param3) { //perform necessary actions //set up a requestUr ...

Typescript: Removing signatures with a filter

I am encountering a TypeScript error stating that .filter has no signatures. I'm unsure of how to resolve this issue. interface IDevice { deviceId: string; deviceName?: string; } const joinRoom = ({ userId, deviceId, deviceName }: IRoomParams ...

The HTML template remains unchanged unless explicitly triggering detectChanges() with change detection set to onpush

In my Angular component, I am utilizing change detection on push. The component includes an input that gets modified by the component when the route changes. However, I noticed that simply assigning a new reference to the input and making modifications d ...

Is it possible for me to listen to an AngularJS event using regular JavaScript, outside of the Angular framework?

Is it possible to listen to an event triggered in AngularJS using regular JS (outside of Angular)? I have a scenario where an event is being emitted using RxJS in Angular 2. Can I observe that event from pure JS? Here's some example pseudo code: imp ...

Replicating the run configurations generated by the Angular2 CLI plugin in Eclipse

Currently using Eclipse Neon (4.6) along with the Angular 2 plugin, which provides run configurations such as ng build and ng serve. These configurations utilize the Angular CLI to execute build or serve commands within the project. It appears that these c ...

What is the best way to incorporate the trix-editor into an Angular 2 application?

I've been struggling to incorporate the Trix editor into my Angular application. I can't seem to find any resources or npm packages that explain how to install the Trix editor in an Angular 2 app. Can anyone provide guidance on where to find the ...

Utilize the value of one variable to determine access to another variable in Javascript

I am working with several boolean variables and I want to create a new variable that keeps track of the most recently changed boolean variable. This way, every time a new boolean variable is modified, I can toggle the previous one. If you have any ideas o ...

What is the best way to simulate DOCUMENT dependency injection for unit tests using Jest?

Currently, I have integrated a component known as 'A' which relies on the document object for its functionality. The component features a method called onClose(), which utilizes the document object service to retrieve elements using querySelector ...

Instructions for enabling the touch slider feature in the Igx carousel component with Angular 6 or higher

Looking to enable the touch slider for Igx carousel using angular 6+? I am trying to implement the igx carousel for image sliding with reference from a stackblitz demo (https://stackblitz.com/edit/github-j6q6ad?file=src%2Fapp%2Fcarousel%2Fcarousel.compone ...

When running the command `npm audit fix --force`, an error is triggered stating that the data path ".builders['app-shell']" must contain the mandatory property 'class'

After installing a package, I received the following message: added 1 package from 8 contributors and audited 49729 packages in 23.754s found 25 vulnerabilities (1 low, 24 high) run `npm audit fix` to fix them, or `npm audit` for details I proceeded to ...

React - A high-capacity file selector component designed to efficiently handle large numbers of files being selected

I am in search of a component that can retrieve a list of files from the user without actually uploading them. The upload functionality is already in place; I simply require a list of selected files. The component must meet the following criteria: Restric ...

Tips on avoiding issues with the backslash character in Typescript

Can someone help me with creating a regular expression in Typescript that can match the decimal separator character followed by a sequence of zeros in a string? I have tried to come up with an expression as shown below: /\.0+\b/g However, since ...

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

Vuetify 3 does not display dialogs

I am attempting to integrate vuetify 3.alpha with vue 3. Below are the files I am working with: Temp.vue (obtained from vuetify example) <template> <div class="text-center"> <v-dialog v-model="dialog" w ...

Is there a way to simultaneously filter the mat table data source and its related asynchronous properties?

Scenario: My current setup consists of angular version 9.1.7, angular-material version 9.2.3, macOS version 10.14.6, and ngrx libraries (store, data, entity) version 9.1.2 Description: I currently have a functional material table with a MatTableDataSourc ...

Using parameters in data binding with Angular 5

I have a scenario where I need to categorize and display data fetched from my database in JSON format. The data consists of various columns such as id, name, message, and type. My goal is to organize this data into different div elements based on the conte ...

Optimal method for passing data from a function that utilizes a callback

My service involves calling a method with a callback: import {someDataBaseFunction} from 'something/somthing'; class MyService{ myServiceFunction(param1, param2){ someDataBaseFunction(param1, param2, (error) => { if ( ...

Angular Universal in combination with AngularFire server experiences a hanging issue due to the first() pipe

I am currently developing an angular/firestore application that requires SSR capabilities. I have integrated angular universal into the project and everything seems to be functioning properly until I utilize the first() pipe on any of the firestore calls, ...

Step-by-step guide on how to stop CDK Drop depending on a certain condition

I'm trying to figure out how to disable dropping using CDK based on certain conditions. Specifically, I want the drop functionality to be disabled if the list I'm attempting to drop into is empty. I haven't been able to find a solution withi ...

Is there a way to insert data from one table into a MySQL Table in Drizzle and update the entry if it already exists?

My goal is to utilize Drizzle for inserting data into a table and updating it if the key already exists. In MySQL, the code would look like this: INSERT INTO myTable1(field1,field2,field3,field4) SELECT fieldOne,fieldTwo,fieldThree,fieldFour FROM myTable2 ...