All Projects → alonronin → Mockingoose

alonronin / Mockingoose

Licence: unlicense
A Jest package for mocking mongoose models

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Mockingoose

Fullstack Shopping Cart
MERN stack shopping cart, written in TypeScript
Stars: ✭ 82 (-70.61%)
Mutual labels:  mongoose, jest
Rest
REST API generator with Node.js, Express and Mongoose
Stars: ✭ 1,663 (+496.06%)
Mutual labels:  mongoose, jest
Node Express Boilerplate
A boilerplate for building production-ready RESTful APIs using Node.js, Express, and Mongoose
Stars: ✭ 890 (+219%)
Mutual labels:  mongoose, jest
Nest User Auth
A starter build for a back end which implements managing users with MongoDB, Mongoose, NestJS, Passport-JWT, and GraphQL.
Stars: ✭ 145 (-48.03%)
Mutual labels:  mongoose, jest
Typescript Express Starter
🚀 TypeScript Express Starter
Stars: ✭ 238 (-14.7%)
Mutual labels:  mongoose, jest
ng-nest-cnode
Angular 10 Front-End and Nestjs 7 framework Back-End build Fullstack CNode
Stars: ✭ 17 (-93.91%)
Mutual labels:  jest, mongoose
Nodejs Backend Architecture Typescript
Node.js Backend Architecture Typescript - Learn to build a backend server for Blogging platform like Medium, FreeCodeCamp, MindOrks, AfterAcademy - Learn to write unit and integration tests - Learn to use Docker image - Open-Source Project By AfterAcademy
Stars: ✭ 1,292 (+363.08%)
Mutual labels:  mongoose, jest
Mongoose Typescript Example
Stars: ✭ 156 (-44.09%)
Mutual labels:  mongoose, jest
Blog Service
blog service @nestjs
Stars: ✭ 188 (-32.62%)
Mutual labels:  mongoose, jest
wily
Build Node.js APIs from the command line (Dead Project 😵)
Stars: ✭ 14 (-94.98%)
Mutual labels:  jest, mongoose
ack-nestjs-mongoose
NestJs Boilerplate. Authentication (OAuth2), Mongoose, MongoDB , Configuration, Multi Languages (i18n), etc. Advance Example 🥶. NestJs v8 🥳🎉. Production Ready 🚀🔥
Stars: ✭ 81 (-70.97%)
Mutual labels:  jest, mongoose
Mevn Boilerplate
A fullstack boilerplate with Mongo, ExpressJS, VueJS and NodeJS.
Stars: ✭ 277 (-0.72%)
Mutual labels:  mongoose
Bs Jest
BuckleScript bindings for Jest
Stars: ✭ 255 (-8.6%)
Mutual labels:  jest
jest-runner-stylelint
Stylelint runner for Jest
Stars: ✭ 18 (-93.55%)
Mutual labels:  jest
graceful
Gracefully exit server (Koa), database (Mongo/Mongoose), Redis clients, and job scheduler (Redis/Bull)
Stars: ✭ 37 (-86.74%)
Mutual labels:  mongoose
Testing Library Docs
docs site for @testing-library/*
Stars: ✭ 284 (+1.79%)
Mutual labels:  jest
Nuxt Blog
基于Nuxt.js服务器渲染(SSR)搭建的个人博客系统
Stars: ✭ 277 (-0.72%)
Mutual labels:  mongoose
jest-mock-date-examples
Different approaches to mocking the Date in Jest tests
Stars: ✭ 22 (-92.11%)
Mutual labels:  jest
Fable.Jester
Fable bindings for jest and friends for delightful Fable testing.
Stars: ✭ 28 (-89.96%)
Mutual labels:  jest
node-express-mongoose-sqlize
node, express, mongoose, sqlize, passport, jwt
Stars: ✭ 17 (-93.91%)
Mutual labels:  mongoose

Mockingoose CircleCI

logo

A Jest package for mocking mongoose models

Installation

$ npm i mockingoose -D

Import the library

// using commonJS
const mockingoose = require('mockingoose').default;

// using es201x
import mockingoose from 'mockingoose';

Usage

// user.js
import mongoose from 'mongoose';
const { Schema } = mongoose;

const schema = Schema({
  name: String,
  email: String,
  created: { type: Date, default: Date.now },
});

export default mongoose.model('User', schema);

mockingoose(Model).toReturn(obj, operation = 'find')

Returns a plain object.

// __tests__/user.test.js
import mockingoose from 'mockingoose';

import model from './user';

describe('test mongoose User model', () => {
  it('should return the doc with findById', () => {
    const _doc = {
      _id: '507f191e810c19729de860ea',
      name: 'name',
      email: '[email protected]',
    };

    mockingoose(model).toReturn(_doc, 'findOne');

    return model.findById({ _id: '507f191e810c19729de860ea' }).then(doc => {
      expect(JSON.parse(JSON.stringify(doc))).toMatchObject(_doc);
    });
  });

  it('should return the doc with update', () => {
    const _doc = {
      _id: '507f191e810c19729de860ea',
      name: 'name',
      email: '[email protected]',
    };

    mockingoose(model).toReturn(doc, 'update');

    return model
      .update({ name: 'changed' }) // this won't really change anything
      .where({ _id: '507f191e810c19729de860ea' })
      .then(doc => {
        expect(JSON.parse(JSON.stringify(doc))).toMatchObject(_doc);
      });
  });
});

mockingoose(Model).toReturn(fn, operation = 'find')

Allows passing a function in order to return the result.

You will be able to inspect the query using the parameter passed to the function. This will be either a Mongoose Query or Aggregate class, depending on your usage.

You can use snapshots to automatically test that the queries sent out are valid.

// __tests__/user.test.js
import mockingoose from 'mockingoose';
import model from './user';

describe('test mongoose User model', () => {
  it('should return the doc with findById', () => {
    const _doc = {
      _id: '507f191e810c19729de860ea',
      name: 'name',
      email: '[email protected]',
    };
    const finderMock = query => {
      expect(query.getQuery()).toMatchSnapshot('findById query');

      if (query.getQuery()._id === '507f191e810c19729de860ea') {
        return _doc;
      }
    };

    mockingoose(model).toReturn(finderMock, 'findOne'); // findById is findOne

    return model.findById('507f191e810c19729de860ea').then(doc => {
      expect(JSON.parse(JSON.stringify(doc))).toMatchObject(_doc);
    });
  });
});

mockingoose(Model).reset(operation = undefined)

will reset Model mock, if pass an operation, will reset only this operation mock.

it('should reset model mock', () => {
  mockingoose(model).toReturn({ name: '1' });
  mockingoose(model).toReturn({ name: '2' }, 'save');

  mockingoose(model).reset(); // will reset all operations;
  mockingoose(model).reset('find'); // will reset only find operations;
});

you can also chain mockingoose#ModelName operations:

mockingoose(model)
  .toReturn({ name: 'name' })
  .toReturn({ name: 'a name too' }, 'findOne')
  .toReturn({ name: 'another name' }, 'save')
  .reset('find');

mockingoose.resetAll()

will reset all mocks.

beforeEach(() => {
  mockingoose.resetAll();
});

Operations available:

  • [x] find - for find query
  • [x] findOne - for findOne query
  • [x] count - for count query (deprecated)
  • [x] countDocuments for count query
  • [x] estimatedDocumentCount for count collection documents
  • [x] distinct - for distinct query
  • [x] findOneAndUpdate - for findOneAndUpdate query
  • [x] findOneAndRemove - for findOneAndRemove query
  • [x] update - for update query
  • [x] save - for create, and save documents Model.create() or Model.save() or doc.save()
  • [x] remove - for remove query
  • [x] deleteOne - for deleteOne query
  • [x] deleteMany - for deleteMany query
  • [x] aggregate - for aggregate framework

Notes

The library is built with Typescript and typings are included.

All operations work 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:

    mockingoose(model).toReturn(new Error('My Error'), 'save');
    
    return model.create({ name: 'name', email: '[email protected]' }).catch(err => {
      expect(err.message).toBe('My Error');
    });
    
  • you can mock .populate in your mocked result just be sure to change the Schema's path to appropriate type (eg: Object | Mixed):

    User.schema.path('foreignKey', Object);
    
    const doc = {
      email: '[email protected]',
      foreignKey: {
        _id: '5ca4af76384306089c1c30ba',
        name: 'test',
        value: 'test',
      },
      name: 'Name',
      saveCount: 1,
    };
      
    mockingoose(User).toReturn(doc);
      
    const result = await User.find();
      
    expect(result).toMatchObject(doc);
    
  • 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.

Recent Changes:

  • mockingoose.ModelName is deprecated, mockingoose(Model) is the now the recommended usage, with Model being a Mongoose model class.

    Alternatively, you may pass a string with the model name.

  • mockingoose(Model).toReturn((query) => value) can now take also take a function as a parameter.

    The function is called with either a Query or Aggregate object from Mongoose, depending on the request. This allows tests to ensure that proper queries are sent out, and helps with regression testing.

Shoutout to our amazing community

Stargazers

Stargazers repo roster for @alonronin/mockingoose

Forkers

Forkers repo roster for @alonronin/mockingoose

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].