Typescript - 具有映射类型的模拟接口 [英] Typescript - Mock interface with mapped types
问题描述
出于测试目的,我希望能够创建一个实现接口的对象,仅使用我测试所需的功能,而无需手动维护具有所有可能属性的模拟对象.通常,我一次只使用一个函数,因此不需要定义所有其他函数,但我不希望 TS 一直抱怨缺少属性.
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.
例如,我有一个接口 IFoo
:
For example, I have an interface IFoo
:
interface IFoo {
myFunc(): string;
otherFunc(): number;
}
我尝试创建一个映射类型,它将 jest.Mock<{}>
分配给 IFoo
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<{}>
};
这样称呼:
const mockFoo: Mockify<IFoo> = {
otherFunc: {
// Mocked function behavior
}
}
这种方法的问题是 TS 抱怨传递给 Mockify 的对象缺少 myFunc
属性.
The problem with this approach is that TS complains about the missing myFunc
property on the object passed to Mockify.
我也尝试过 Mockify
来忽略缺少的属性,但是我的类型定义与 IFoo
和其他一些依赖于 IFoo
在抱怨.我也可以将所有属性定义为 optionnal,但从概念上讲我不喜欢那样.
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.
感谢您的帮助!
推荐答案
我可以在我的映射类型定义中设置所有属性可选:
I can make all properties optionnal in my mapped type definition:
type Mockify<T> = {
[P in keyof T]?: jest.Mock<{}>
};
这相当于每次使用 Mockify
时都使用 Partial
.
This is equivalent to use Partial
everytime I use Mockify
.
然后,当稍后使用我的模拟对象时,类型断言将其转换回原始界面,每个人都很高兴
Then, when using my mockified object later on, type assertion casts it back to the original interface and everybody's happy
const mockFoo: Mockify<IFoo> = {
otherFunc: {
// Mocked function behavior
}
}
dependentFunc(mockFoo as IFoo);
这篇关于Typescript - 具有映射类型的模拟接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!