Reputation: 33
My requirement is to use stubbing in unit testing script to bypass some actual mysql query using a mock data. I'm using mocha testing framework and chai. I don't know how to use mock data to bypass the mysql query.
I tried with some testing variable and if the variable is true i'm just bypassing the mysql query with predefined mock data. But that's not a proper proceedure. So can you please explain me how to use sinon stub to overcome mysql using mock data.
let query_response = await sequelize.query("select * from `" + table_name + "` where email='" + data.user + "' and name = '" + name + "' " + pre_name + ";", {
type: sequelize.QueryTypes.SELECT
});
In unit testing i need to bypass this query and give response using some mock data. The response should be like this,
[ { id: '3',
xyz_id: 'Z1455264',
vir_id: '264_3',
name: 'XYZ',
pre_name: 'abc',
value: 1 },
{ id: '32',
xyz_id: 'Z1455dd264',
vir_id: '26s4_3',
name: 'XYZQ',
pre_name: 'abdc',
value: 1 }];
Upvotes: 2
Views: 3365
Reputation: 2005
There are a bunch of ways (dependency injection, runtime module replacement, etc) to do it and a bunch of libraries to help you. It's up to the level of abstraction you have and how neat you want it. The quick and dirty way is to use something like proxyquire and a mocking library like testdouble.
With your sut.js (the module/system you will be testing), you would have:
const sequelize = require('sequelize')
// ...
exports.doSomething = async function () {
await sequelize.query("select * from `" + table_name + "` where email='" + data.user + "' and name = '" + name + "' " + pre_name + ";", {
type: sequelize.QueryTypes.SELECT
})
}
And in your test you could do the following (agnostic to the testing framework):
const proxyquire = require('proxyquire')
const td = require('testdouble')
const sequelize = require('sequelize')
const query = td.function()
const sut = proxyquire('/path/to/your/sut.js', { 'sequelize': { query } })
const expected = [{
id: '3',
xyz_id: 'Z1455264',
vir_id: '264_3',
name: 'XYZ',
pre_name: 'abc',
value: 1
}, {
id: '32',
xyz_id: 'Z1455dd264',
vir_id: '26s4_3',
name: 'XYZQ',
pre_name: 'abdc',
value: 1
}];
td.when(query("select * from `<the_table_name>` where email='<the_email>'...", { type: sequelize.QueryTypes.SELECT })).thenResolve(expected);
// assert whatever you need from sut.doSomething()
Upvotes: 1