cklanac
8/17/2017 - 11:40 AM

Test the .catch() condition of an endpoint with a mongoose query

Test the .catch() condition of an endpoint with a mongoose query

'use strict';

const chai = require('chai');
const chaiHttp = require('chai-http');
const spies = require('chai-spies');

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

// make the `should` syntax available throughout this module
chai.should();

const { app } = require('../server');
const { TEST_DB } = require('../config');
const { Cat } = require('../cat/model');

chai.use(chaiHttp);
chai.use(spies);

describe('Mocha and Chai', function () {
  it('should be properly setup', function () {
    true.should.be.true;
  });
});

describe('API', function () {
  before(function () {
    // This connection applies to both the test script and the app being tested 
    return mongoose.connect(TEST_DB, { useMongoClient: true }).catch(err => {
      console.error('ERROR: Mongoose failed to connect! Is the database running?');
      console.error(err);
    });
  });

  beforeEach(function () {
    // Seed database
    const tizzy = new Cat({ name: 'Tizzy' });
    const fuzzy = new Cat({ name: 'Fuzzy' });
    const pixie = new Cat({ name: 'Pixie' });
    return Cat.insertMany([tizzy, fuzzy, pixie]);
  });

  afterEach(function () {
    return mongoose.connection.dropDatabase();
  });

  after(function () {
    return mongoose.disconnect();
  });

  describe('GET /v1/cats', function () {
    it('should respond with status 200 and an array of results', function () {
      return chai
        .request(app)
        .get('/v1/cats')
        .then(function (res) {
          res.should.have.status(200);
          res.should.be.json;
          res.body.should.have.lengthOf(3);
        });
    });
  });

  describe('Force Mongoose Errors.', function () {
    describe('Faulty find method', function () {
      const _find = Cat.find;
      beforeEach(function(){
        Cat.find = function () {
          return Promise.reject('forced error');
        };
      });
      afterEach(function(){
        Cat.find = _find; 
      }); 
      it('should respond with a server error', function () {
        // test code
        
        const spy = chai.spy();
        return chai
          .request(app)
          .get('/v1/cats')
          .then(spy)
          .catch((err) => {
            const res = err.response;
            res.should.have.status(500);
          })
          .then(() => {
            spy.should.not.have.been.called();
          });
      });
    }); 
  });

});
'use strict';

const express = require('express');
const router = express.Router();

const { Cat } = require('./model');

router.get('/', (req, res) => {
  Cat.find()
    .then(list => {
      res.json(list);
    })
    .catch(err => {
      res.status(500).json({ message: 'Internal server error' });
      console.error(err);
    });
});

module.exports = { router };