繁体   English   中英

模拟MongoDB中的数据以满足Jest中的TypeScript

[英]Mocking data from MongoDB to satisfy TypeScript in Jest

我正在为扩展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; 行业:字符串; }'不能分配给'IAccount'类型的参数。 输入'{name:string; 行业:字符串; ''缺少类型'IAccount'的以下属性:_id,increment,model和52 more.ts(2345)

创建满足TypeScript用于测试目的的对象的最简单方法是什么?

一种选择是创建一个与预期类型匹配的模拟...

......但对于高度复杂的类型来说,这可能非常困难。

另一个选项是告诉TypeScript您希望mock通过编译时类型检查。

你可以通过为你的模型分配any类型来做到这一点:

function getData(account: IAccount){
  return account;
}

const account: any = {  // <= use type "any"
  name: 'Test account name',
  industry: 'test account industry'
}

getData(account);  // <= no error

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM