简体   繁体   中英

Mocking data from MongoDB to satisfy TypeScript in Jest

I am creating a TypeScript interface for each model that extends mongoose.Document.

import mongoose, { Document } from 'mongoose';

export interface IAccount extends Document {
  _id: mongoose.Types.ObjectId;
  name: string;
  industry: string;
}

The schema is then exported with the interface:

export default mongoose.model<IAccount>('Account', accountSchema);

The problem is that in Jest, creating an object with the properties required for the function being testing isn't enough, TypeScript complains about all the missing fields.

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

const account = {
  name: 'Test account name',
  industry: 'test account industry'
}

getData(account);

Argument of type '{ name: string; industry: string; }' is not assignable to parameter of type 'IAccount'. Type '{ name: string; industry: string; }' is missing the following properties from type 'IAccount': _id, increment, model, and 52 more.ts(2345)

What is the simplest way to create an object that satisfies TypeScript for testing purposes?

One option is to create a mock that matches the expected type...

...but that can be very difficult for highly complex types.

The other option is to tell TypeScript you want your mock to pass through compile-time type checking.

You can do that by assigning your mock the type 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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