Mockingoose
A Jest package for mocking mongoose models
Installation
$ npm i mockingoose -D
Import the library
// using commonJSconst mockingoose = default; // using es201x;
Usage
// user.js;const Schema = mongoose; const schema = ;
mockingoose#ModelName#toReturn(obj, operation = 'find')
// __tests__/user.test.js;;
mockingoose#ModelName#reset(operation = undefined)
will reset Model mock, if pass an operation, will reset only this operation mock.
you can also chain mockingoose#ModelName
operations:
mockingooseUser ;
mockingoose#resetAll()
will reset all mocks.
Operations available:
-
find
- for find query -
findOne
- for findOne query -
count
- for count query -
distinct
- for distinct query -
findOneAndUpdate
- for findOneAndUpdate query -
findOneAndRemove
- for findOneAndRemove query -
update
- for update query -
save
- for create, and save documentsModel.create()
orModel.save()
ordoc.save()
-
remove
- for remove query -
deleteOne
- for deleteOne query -
deleteMany
- for deleteMany query
Notes
All operations works with exec
, promise
and callback
.
if you are using Model.create
and you don't pass a mock with mockingoose,
you'll receive the mongoose created doc (with ObjectId and transformations)
validations are working as expected.
the returned document is an instance of mongoose Model.
update
operation returns original mocked object.
you can simulate Error by passing an Error to mockingoose:
mockingooseUser; return User
no connection is made to the database (mongoose.connect is jest.fn())
will work with node 6.4.x. tested with mongoose 4.x and jest 20.x.
check tests for more, feel free to fork and contribute.