Unit testing Sails JS 1.0 helpers

Viewed 388

I'm trying to setup unit testing in my SailsJS 1.0 application. I want to mock the DB and not have to run sails lift to test.

I have a very simple actions2 (node machine) helper that queries the DB:

fn: async function (inputs, exits) {
  Users.findOne({id: inputs.userId})
    .exec((err, data) => {
      if (err) {
        return exits.error(err);
      }

      if (!data) {
        return exits.success([]);
      }

      return exits.success(data);
    });
}

I am using mocha as my test framework. How can I mock Users?

1 Answers

You can use sinon to stub the function of your models.

const sinon = require('sinon');

it('should something', async () => {
  const sandbox = createSandbox();
  const User = require('/path/to/User');
  sandbox.stub(User, 'findOne')
    .returns({
      exec: (callback) => {
        callback(null, { data: 'you want returned' })
      }
    })
  sandbox.restore();   // restores User.findOne to its original functionality so that other tests will not be contaminated
});
Related