samedi 28 mai 2016

How to test save/update/delete models from MongoDB

Try to write some tests for my model. What I need? I think:

  1. Before all - connect to test database
  2. Before each / after each - remove collections (I need empty db?)
  3. After all - disconnect.

Ok, but I can't correctly write this, to test with mocha and chai.

My model (Provider.js)

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const providerSchema = new Schema({
  name: { type: String, required: true },
  location: String,
  phone: String,
  members: Array,
  created_at: Date,
  updated_at: Date
})

const Provider = mongoose.model('Provider', providerSchema)
module.exports = Provider

My provider_test.js:

const mongoose = require('mongoose')
require('../models/provider')(mongoose)
const Provider = mongoose.model('Provider')

const chai = require('chai')
const should = chai.should
const expect = chai.expect

describe('Provider Model Unit Tests:',() => {

  before((done) => {
    mongoose.connect('mongodb://localhost/db_test')
    Provider.remove({}, (err) => {
      if (err) console.log(err)
    })
    done()
  })

  describe('Testing the save method', () => {
    it('Should be able to save without problems', () => {
      provider = new Provider({
        name: 'User 2',
        location: 'City',
        phone: '+123 12 32 11',
      })
      provider.save((err) => {
        should.not.exist(err)
        done()
      })
    })

    it('Should not be able to save an provider without a title', () => {
      provider = new Provider({
        name: '',
        location: 'City',
        phone: '+123 12 32 11',
      })

      provider.save((err) => {
        should.exist(err)
        done()
      })
    })
  })
})

Run test comand is: mocha

My provider_test placed into 'test' folder.

All tests pass, but... If I change in second test case should.exist(err) -> should.not.exist(err) - all tests pass again. If I try to console.log(err) in second test case - I see error.

Also, I can see my model (with name from test) in database. After new run - new model creates, and old deleted.

Aucun commentaire:

Enregistrer un commentaire