DEV Community

loading...
Cover image for Unit Testing Sequelize 4 ES6 class models

Unit Testing Sequelize 4 ES6 class models

Hugo Di Francesco
Developer, JavaScript, CSS and web. Writing at Code with Hugo.
Originally published at codewithhugo.com on ・2 min read

In “Using ES6 classes for Sequelize 4 models” we explored how to define Sequelize models using ES6 classes.One of the benefits of such an approach is that it allows easy unit testing, it allows you to instantiate the model without the baggage of all of Sequelize (and/or a database).

The examples will use Jest module auto-mocking but should be portable to other module mocking libraries (eg. Proxyquire) with some modifications.

We’ll be testing the following model:

const { Model } = require('sequelize');

class MyModel extends Model {
  static init() {
    return super.init(
      // Config, see "Using ES6 classes for Sequelize 4 models"
    );
  }

  isAvailable (date) {
    if (!Array.isArray(this.meetings)) {
      throw new Error('meetings should be eager-loaded');
    }
    return !this.meetings.find(
      ({ startDate, endDate }) => (startDate < date && endDate > date)
    );
  }
}

module.exports = MyModel;

Enter fullscreen mode Exit fullscreen mode

At the module level, we want to:

  • mock out Sequelize
  • import the model

In the test:

  • Instantiate the model that we’ve defined (without crashing)
  • Set some properties on that instance
  • Run some methods
  • Assert on the output
jest.mock('sequelize');
const Model = require('./model');

test('It should not throw when passed a model containing an empty list of meetings', () => {
  const model = new Model();
  model.meetings = [];
  expect(model.isAvailable.bind(null, new Date(Date.now())).not.toThrow();
});

Enter fullscreen mode Exit fullscreen mode

Alternative with Object.assign

If we’re setting more than a single instance property, using Object.assign can be easier to manage:

jest.mock('sequelize');

const Model = require('./model');

test('It should not throw when passed a model containing an empty list of meetings', () => {
  const model = Object.assign(
    new Model(),
    {
      meetings: []
    }
  );
  expect(model.isAvailable.bind(null, new Date(Date.now())).not.toThrow();
});

Enter fullscreen mode Exit fullscreen mode

Using ES6 classes with Sequelize makes testing easier and more natural, sign up to the newsletter to stay in the loop for the upcoming Sequelize ES6 Cheat Sheet.

Elevate

Discussion (0)