'How to mock interface with Jest without creating an instance
I know we can do it in Kotlin but I did not find it with Jest. I have complex interfaces and array of those interfaces and I do not want to specify all values of all attributes of the interface. Below I made an example of what I would like:
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)
Solution 1:[1]
Interfaces don't exist in JS' runtime, it's purely a TS feature which is used for type assertions during compilation. Therefore, it's impossible to generate a correct mock based on interface in JS runtime. However, it's possible with classes.
Considering that you want to create a mock without creating an instance, you can cast an empty object to the desired type. However, keep in mind, that the cast object doesn't have any properties by default and access to 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 // works
user.name = undefined; // fails, wrong type
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | satanTime |