Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock mongoose?

I should run tests on node+express+mongoose+swagger app without mongodb, I need module to mock mongoose (only for tests). I tried mock-mongoose and mockgoose, but I had errors :( Maybe I failed.. or this modules can't help me I hope for your ideas!

I created example skeleton: https://github.com/miroslav-grabinskiy/swagger-server-mock-tested

I need to mock only in tests, and I don't need to test mongoose, like a:

Model.find()

I need test api (routes) like in link

P.S. mock-mongoose not working with promises :(

like image 252
Jackson Avatar asked Jul 24 '17 15:07

Jackson


1 Answers

I have found the solution - use mockgoose:

"use strict";

const config = require(appRoot + '/config');
const Mongoose = require('mongoose').Mongoose;
const mongoose = new Mongoose();

const DB_NAME = "rbTest";
const DOCKER_MONGODB_URI = "mongodb://mongo:27017/" + DB_NAME;
const LOCAL_MONGODB_URI = "mongodb://localhost:27017/" + DB_NAME + "?socketTimeoutMS=120000";
const myMongo = process.env.DOCKER ? DOCKER_MONGODB_URI : LOCAL_MONGODB_URI;

mongoose.Promise = global.Promise;

if (process.env.NODE_ENV === 'testing') {
  const Mockgoose = require('mockgoose').Mockgoose;
  const mockgoose = new Mockgoose(mongoose);

  mockgoose.prepareStorage().then(function() {
    mongoose.connect(myMongo, function(err) {
      console.log('connected');
    });
  });
} else {
  mongoose.connect(myMongo, config.get('mongoose:options'));
}

module.exports = mongoose;
like image 128
Jackson Avatar answered Oct 01 '22 03:10

Jackson