For testing purpose, I'd like to be able to create an object implementing an interface, only with function I need for my test, without having to manually maintain a mock object with all possible properties. Generally, I'm using one function at a time, so don't need to define all others but I don't want TS to keep complaining about missing properties.
For example, I have an interface IFoo :
interface IFoo {
myFunc(): string;
otherFunc(): number;
}
I tried to create a mapped type, which assign jest.Mock<{}> to all properties of IFoo
type Mockify<T> = {
[P in keyof T]: jest.Mock<{}>
};
Calling it like this:
const mockFoo: Mockify<IFoo> = {
otherFunc: {
// Mocked function behavior
}
}
The problem with this approach is that TS complains about the missing myFunc property on the object passed to Mockify.
I also tried Mockify<Partial<IFoo>> to ignore missing properties, but then my type defintion is different from IFoo and some other functions depending of IFoo are complaining. I could also define all properties as optionnal, but conceptually I don't like that.
I have the feeling that mapped types could make the job, but I maybe don't have the right approach.
Thanks for your help!
Aucun commentaire:
Enregistrer un commentaire