我正在为每个扩展mongoose.Document的模型创建一个TypeScript接口。
import mongoose, { Document } from 'mongoose';
export interface IAccount extends Document {
_id: mongoose.Types.ObjectId;
name: string;
industry: string;
}然后将该模式与接口一起导出:
export default mongoose.model<IAccount>('Account', accountSchema);问题是,在Jest中,创建一个具有被测试函数所需属性的对象是不够的,TypeScript会抱怨所有缺少的字段。
function getData(account: IAccount){
return account;
}
const account = {
name: 'Test account name',
industry: 'test account industry'
}
getData(account);'{ name: string;行业: string;}‘类型的参数不能赋值给'IAccount’类型的参数。类型'{ name: string;行业: string;}‘缺少类型’IAccount‘的以下属性:_id、increment、model和52 more.ts(2345)
出于测试目的,创建满足TypeScript的对象的最简单方法是什么?
发布于 2019-06-08 06:02:38
一种选择是创建一个与预期类型匹配的模拟...
对于高度复杂的类型来说,这可能是非常困难的...but。
另一种选择是告诉TypeScript您希望您的模拟通过编译时类型检查。
您可以通过将any类型分配给模拟来实现这一点
function getData(account: IAccount){
return account;
}
const account: any = { // <= use type "any"
name: 'Test account name',
industry: 'test account industry'
}
getData(account); // <= no errorhttps://stackoverflow.com/questions/56481707
复制相似问题