Tuesday 16 May 2017

Sinon stub Mongoose Model Update/Save

I have a Express route that updates a Mongoose model in MongoDB. I am trying to unit test the route using Sinon. I'm able to stub the model's find method successfully, but not able to do it for update, save. The update is happening in the database, and so more of an integration test.

Based on Stubbing a Mongoose model with Sinon I tried this,

....
let User = require('./../models/users.js');
var supertest = require('supertest');
var mongoose = require('mongoose');
var modelStub = sinon.stub(mongoose.Model,'update');
// var modelStub = sinon.stub(User.prototype,'update');
var url = supertest.agent("http://localhost:8080");
var token = '';
function loginUser() {              
 return function(done) {
    url
    .post('/login')
    .send({"username": "admin", "password":"admin"})
    .expect(200)
    .end(onResponse);
       function onResponse(err, res) {
      if (err) return done(err);
      token = res.body.token;
      return done();
    }
   };
};


 describe("Testing PUT route", function(err){
    beforeEach(()=> {
         console.log('in beforeEach');
         modelStub.yields(null,{ ok: 1, nModified: 1, n: 1 });
            });
    describe("yielding", function(err){
            it('login', loginUser());
        it("should check changepassword route", function(done){
                url
                .put('/dashboard/changepassword')
                .set({"Authorization": token})
                .send({"username":"admin","password":"admin"})
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function(err,res){
                    expect(res.body.ok).to.be.equal(1);
                done();
            });
            });
    });
});

The test passes, but the update happens in the database. Please help.



via user2693135

No comments:

Post a Comment