{"id":13989735,"url":"https://github.com/alonronin/mockingoose","last_synced_at":"2025-05-15T23:03:55.467Z","repository":{"id":22460776,"uuid":"96312232","full_name":"alonronin/mockingoose","owner":"alonronin","description":"A Jest package for mocking mongoose models","archived":false,"fork":false,"pushed_at":"2024-04-02T11:56:19.000Z","size":697,"stargazers_count":386,"open_issues_count":9,"forks_count":49,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-08T10:16:32.351Z","etag":null,"topics":["jest","mongoose","testing"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/mockingoose","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"unlicense","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alonronin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"custom":["https://www.paypal.me/alonronin"]}},"created_at":"2017-07-05T11:31:31.000Z","updated_at":"2025-03-08T01:12:18.000Z","dependencies_parsed_at":"2024-04-02T12:52:56.811Z","dependency_job_id":"2f6afb4c-2ef0-44db-96df-70bc9bd93c15","html_url":"https://github.com/alonronin/mockingoose","commit_stats":{"total_commits":189,"total_committers":14,"mean_commits":13.5,"dds":"0.14814814814814814","last_synced_commit":"fa7226d4abcd00cf6632b88bebd99fa6f66bc258"},"previous_names":[],"tags_count":40,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alonronin%2Fmockingoose","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alonronin%2Fmockingoose/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alonronin%2Fmockingoose/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alonronin%2Fmockingoose/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alonronin","download_url":"https://codeload.github.com/alonronin/mockingoose/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254436944,"owners_count":22070946,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["jest","mongoose","testing"],"created_at":"2024-08-09T13:02:01.096Z","updated_at":"2025-05-15T23:03:55.434Z","avatar_url":"https://github.com/alonronin.png","language":"JavaScript","funding_links":["https://www.paypal.me/alonronin"],"categories":["JavaScript","TypeScript"],"sub_categories":[],"readme":"# Mockingoose [![CircleCI](https://circleci.com/gh/alonronin/mockingoose/tree/master.svg?style=svg)](https://circleci.com/gh/alonronin/mockingoose/tree/master)\n\n![logo]\n\n\u003e A Jest package for mocking mongoose models\n\n## Installation\n\nWith NPM:\n```bash\n$ npm i mockingoose -D\n```\n\nWith Yarn:\n```bash\n$ yarn add mockingoose -D\n```\n\n## Import the library\n\n```js\nconst mockingoose = require('mockingoose');\n\n```\n\n## Usage\n\n```js\n// user.js\nconst mongoose = require('mongoose');\nconst { Schema } = mongoose;\n\nconst schema = Schema({\n  name: String,\n  email: String,\n  created: { type: Date, default: Date.now },\n});\n\nmodule.exports = mongoose.model('User', schema);\n```\n\n#### mockingoose(Model).toReturn(obj, operation = 'find')\n\nReturns a plain object.\n\n```js\n// __tests__/user.test.js\nconst mockingoose = require('mockingoose');\n\nconst model = require('./user');\n\ndescribe('test mongoose User model', () =\u003e {\n  it('should return the doc with findById', () =\u003e {\n    const _doc = {\n      _id: '507f191e810c19729de860ea',\n      name: 'name',\n      email: 'name@email.com',\n    };\n\n    mockingoose(model).toReturn(_doc, 'findOne');\n\n    return model.findById({ _id: '507f191e810c19729de860ea' }).then(doc =\u003e {\n      expect(JSON.parse(JSON.stringify(doc))).toMatchObject(_doc);\n    });\n  });\n\n  it('should return the doc with update', () =\u003e {\n    const _doc = {\n      _id: '507f191e810c19729de860ea',\n      name: 'name',\n      email: 'name@email.com',\n    };\n\n    mockingoose(model).toReturn(_doc, 'update');\n\n    return model\n      .update({ name: 'changed' }) // this won't really change anything\n      .where({ _id: '507f191e810c19729de860ea' })\n      .then(doc =\u003e {\n        expect(JSON.parse(JSON.stringify(doc))).toMatchObject(_doc);\n      });\n  });\n});\n```\n\n#### mockingoose(Model).toReturn(fn, operation = 'find')\n\nAllows passing a function in order to return the result.\n\nYou will be able to inspect the query using the parameter passed to the function. This will be either a Mongoose [Query](https://mongoosejs.com/docs/api.html#Query) or [Aggregate](https://mongoosejs.com/docs/api.html#Aggregate) class, depending on your usage.\n\nYou can use [snapshots](https://jestjs.io/docs/en/snapshot-testing) to automatically test that the queries sent out are valid.\n\n```js\n// __tests__/user.test.js\nconst mockingoose = require('mockingoose');\nconst model = require('./user');\n\ndescribe('test mongoose User model', () =\u003e {\n  it('should return the doc with findById', () =\u003e {\n    const _doc = {\n      _id: '507f191e810c19729de860ea',\n      name: 'name',\n      email: 'name@email.com',\n    };\n    const finderMock = query =\u003e {\n      expect(query.getQuery()).toMatchSnapshot('findById query');\n\n      if (query.getQuery()._id === '507f191e810c19729de860ea') {\n        return _doc;\n      }\n    };\n\n    mockingoose(model).toReturn(finderMock, 'findOne'); // findById is findOne\n\n    return model.findById('507f191e810c19729de860ea').then(doc =\u003e {\n      expect(JSON.parse(JSON.stringify(doc))).toMatchObject(_doc);\n    });\n  });\n});\n```\n\n#### mockingoose(Model).reset(operation = undefined)\n\nwill reset Model mock, if pass an operation, will reset only this operation mock.\n\n```js\nit('should reset model mock', () =\u003e {\n  mockingoose(model).toReturn({ name: '1' });\n  mockingoose(model).toReturn({ name: '2' }, 'save');\n\n  mockingoose(model).reset(); // will reset all operations;\n  mockingoose(model).reset('find'); // will reset only find operations;\n});\n```\n\nyou can also chain `mockingoose#ModelName` operations:\n\n```js\nmockingoose(model)\n  .toReturn({ name: 'name' })\n  .toReturn({ name: 'a name too' }, 'findOne')\n  .toReturn({ name: 'another name' }, 'save')\n  .reset('find');\n```\n\n#### mockingoose.resetAll()\n\nwill reset all mocks.\n\n```js\nbeforeEach(() =\u003e {\n  mockingoose.resetAll();\n});\n```\n\n### Operations available:\n\n- [x] `find` - for find query\n- [x] `findOne` - for findOne query\n- [x] `count` - for count query (deprecated)\n- [x] `countDocuments` for count query\n- [x] `estimatedDocumentCount` for count collection documents\n- [x] `distinct` - for distinct query\n- [x] `findOneAndUpdate` - for findOneAndUpdate query\n- [x] `findOneAndRemove` - for findOneAndRemove query\n- [x] `update` - for update query (DEPRECATED)\n- [x] `updateOne` - for updateOne query\n- [x] `updateMany` - for updateMany query\n- [x] `save` - for create, and save documents `Model.create()` or `Model.save()` or `doc.save()`\n- [x] `remove` - for remove query (DEPRECATED)\n- [x] `deleteOne` - for deleteOne query\n- [x] `deleteMany` - for deleteMany query\n- [x] `aggregate` - for aggregate framework\n- [x] `insertMany` - for `Model.insertMany()` bulk insert, can also pass `{ lean: true, rawResult: true }` options.\n\n### Notes\n\nAll operations work with `exec`, `promise` and `callback`.\n\n- 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)\n\n- validations are working as expected.\n\n- the returned document is an instance of mongoose Model.\n\n- `deleteOne` and `updateOne` operation returns original mocked object.\n\n- you can simulate Error by passing an Error to mockingoose:\n\n  ```js\n  mockingoose(model).toReturn(new Error('My Error'), 'save');\n\n  return model.create({ name: 'name', email: 'name@email.com' }).catch(err =\u003e {\n    expect(err.message).toBe('My Error');\n  });\n  ```\n\n- you can mock `.populate` in your mocked result just be sure to change \n  the `Schema`'s path to appropriate type (eg: `Object` | `Mixed`):\n  \n  ```js\n  User.schema.path('foreignKey', Object);\n  \n  const doc = {\n    email: 'test@mail.com',\n    foreignKey: {\n      _id: '5ca4af76384306089c1c30ba',\n      name: 'test',\n      value: 'test',\n    },\n    name: 'Name',\n    saveCount: 1,\n  };\n    \n  mockingoose(User).toReturn(doc);\n    \n  const result = await User.find();\n    \n  expect(result).toMatchObject(doc);\n  ```\n\n- you can mock the `Model.exists()` by passing the `findOne` operator. see [Issue #69](https://github.com/alonronin/mockingoose/issues/69)\n  \n- no connection is made to the database (mongoose.connect is jest.fn())\n\n- will work with node 6.4.x. tested with mongoose 4.x and jest 20.x.\n\n- check tests for more, feel free to fork and contribute.\n\n#### Recent Changes:\n\n- `mockingoose.ModelName` is deprecated, `mockingoose(Model)` is the now the recommended usage, with `Model` being a Mongoose model class.\n\n  Alternatively, you may pass a string with the model name.\n\n- `mockingoose(Model).toReturn((query) =\u003e value)` can now take also take a function as a parameter.\n\n  The function is called with either a [Query](https://mongoosejs.com/docs/api.html#Query) or [Aggregate](https://mongoosejs.com/docs/api.html#Aggregate) object from Mongoose, depending on the request. This allows tests to ensure that proper queries are sent out, and helps with regression testing.\n\n[logo]: http://animals.sandiegozoo.org/sites/default/files/2016-12/DwarfMongoose_ZN.jpg\n\n### Shoutout to our amazing community\n\n#### Stargazers\n\n[![Stargazers repo roster for @alonronin/mockingoose](https://reporoster.com/stars/alonronin/mockingoose)](https://github.com/alonronin/mockingoose/stargazers)\n\n#### Forkers\n\n[![Forkers repo roster for @alonronin/mockingoose](https://reporoster.com/forks/alonronin/mockingoose)](https://github.com/alonronin/mockingoose/network/members)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falonronin%2Fmockingoose","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falonronin%2Fmockingoose","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falonronin%2Fmockingoose/lists"}