On my code I have something like:
const getItem = async (itemId) => {
const item = await knex('item').where('id', itemId).first();
console.log(item);
};
And on my test file:
sinon.stub(knex, 'first').resolves({ id: 1 });
knex is imported as const knex = require('Knex')(config)
.
I feel like knex('table_name') creates a different instance and methods are not being mocked.
UPDATE stub only works like this:
const knexStub = sinon.stub(knex, 'from').callsFake(() => ({
where: () => ({
first: () => null
}),
insert: () => sinon.fake()
}));
then in my function like:
const getItem = async (itemId) => {
const item = await knex.from('item').where('id', itemId).first();
console.log(item);
};
I like it better as knex('table_name') but it looks like it's not possible.
sinon doesn't support to stub standalone function, we need to use proxyquire package.
getItem.js
:getItem.test.js
: