Thursday, 1 June 2017

How do I test model based on Bookshelf without actually writing to DB?

If I define my model entities without specifying each table column like this:

let bookshelf = require('../config/database');

require('./role');

var User = bookshelf.Model.extend({
    tableName: 'users',
    role: function() {
        return this.hasOne(Role);
    }
});

module.exports = bookshelf.model('user', User);

How do I create my Mocha/Sinon tests without writing to DB?

I've tried a simple and clearly failing test like this:

var sinon = require('sinon');

var user = require('../../models/user');

var sandbox = sinon.sandbox.create();

describe('User model', function () {

    beforeEach(function () {
        sandbox.stub(user);
    });

    afterEach(function () {
        // completely restore all fakes created through the sandbox
        sandbox.restore();
    });

    it('should return empty set before adding anything', () => {
        sinon.assert.callCount(user, 1);
    });

});

However, actually I got an error message:

  User model
    1) "before each" hook for "should return empty set before adding"


  0 passing (41ms)
  1 failing

  1) User model "before each" hook for "should return empty set before adding":
     TypeError: Attempted to wrap undefined property undefined as function
      at wrapMethod (node_modules/sinon/lib/sinon/util/core/wrap-method.js:70:21)
      at stub (node_modules/sinon/lib/sinon/stub.js:56:44)
      at Object.stub (node_modules/sinon/lib/sinon/collection.js:87:33)
      at Context.<anonymous> (test/models/User.spec.js:10:17)



via Juliano Nunes Silva Oliveira

No comments:

Post a Comment