lundi 25 février 2019

How to mock a Sails.js / Waterline Model during testing

I am trying to mock a Sails Model using sinon.js. I have a problem when I am testing the part where I'm using .fetch() alongside Model.create() to retrieve the newly created row.

Here is my code I want to mock:

...
let newObject = await Object.create(newObjectData).fetch();
...

Here is my test code

const sinon = require('sinon');
const supertest = require('supertest');

describe('Object create action', function() {
  let sandbox;
  beforeEach(function() {
    sandbox = sinon.createSandbox();
  });
  afterEach(function() {
    sandbox.restore();
  });

  it('should create Object', function(done) {

    const objectCreateStub = sandbox.stub(Object, 'create').callsFake(async function(data) {
      console.log(data);
      return {
        key: 'value'
      };
    });
    supertest(sails.hooks.http.app)
      .post(`/objects`)
      .send({
        key: 'value'
      })
      .expect(200)
      .end(done);
  });
});

I have no idea what the Object.create faked function should return in order to .fetch to not throw an error. So, as expected I get this error:

TypeError: Object.create(...).fetch is not a function

What kind of object does Model.create() returns so I could mock it too? Is there a best practice somewhere for testing with Sails and Waterline?

Thanks!

Aucun commentaire:

Enregistrer un commentaire