Coder Social home page Coder Social logo

daveek / mockingoose Goto Github PK

View Code? Open in Web Editor NEW

This project forked from alonronin/mockingoose

0.0 2.0 0.0 241 KB

A Jest package for mocking mongoose models

Home Page: https://www.npmjs.com/package/mockingoose

License: The Unlicense

JavaScript 100.00%

mockingoose's Introduction

Mockingoose

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#ModelName#toReturn(obj, operation = 'find')

// __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.User.toReturn(_doc, 'findOne'); // findById is 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.User.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#ModelName#reset(operation = undefined)

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

it('should reset model mock', () => {
  mockingoose.User.toReturn({ name: '1' });
  mockingoose.User.toReturn({ name: '2' }, 'save');
  
  mockingoose.User.reset(); // will reset all operations;
  mockingoose.User.reset('find'); // will reset only find operations;
})

you can also chain mockingoose#ModelName operations:

mockingoose.User
        .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:

  • 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 documents Model.create() or Model.save() or doc.save()
  • remove - for remove query
  • deleteOne - for deleteOne query
  • deleteMany - for deleteMany query
  • aggregate - for aggregate framework

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:

mockingoose.User.toReturn(new Error('My Error'), 'save');

return User
    .create({ name: 'name', email: '[email protected]' })
    .catch(err => {
      expect(err.message).toBe('My Error');
    })

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.

TODO:

  • Return Jest.fn for Model.save mock
  • Support Model.aggregate

mockingoose's People

Contributors

alonronin avatar ctxhou avatar devinus avatar noamokman avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.