Reputation: 868
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!
Upvotes: 2
Views: 712
Reputation: 868
I figured this out, but I am still unable to say how this works and how it should be tested (correctely)
The problem with my code was: only the last function called in the chain is "async" so when mocking this, only fetch
must be async
Here is my test code
const objectCreateStub = sandbox.stub(Object, 'create').callsFake(function (data) { // Notice here fake function IS NOT async
console.log(data
return {
fetch: async () => { // Here we "mock" the fetch function and it MUST be async !
return newTest
}
};
});
And if you are not using fetch
, mock should look like this:
const objectCreateStub = sandbox.stub(Object, 'create').callsFake(async function(data) { // here fake function MUST BE async
console.log(data)
});
If you understand how Waterline queries works and why we should do this workaround please post another answer because my code works but I still have so many questions :/
Upvotes: 2